user32: Support the MOUSEEVENTF_VIRTUALDESK flag in SendInput().
[wine.git] / programs / cmd / wcmdmain.c
blobb269635c75dc14bcb8d65425ef869067e0fdd169
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_alloc(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 (void) {
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 *q++ = '\r';
354 *q++ = '\n';
355 *q = '\0';
356 while (*p != '\0') {
357 if (*p != '$') {
358 *q++ = *p++;
359 *q = '\0';
361 else {
362 p++;
363 switch (toupper(*p)) {
364 case '$':
365 *q++ = '$';
366 break;
367 case 'A':
368 *q++ = '&';
369 break;
370 case 'B':
371 *q++ = '|';
372 break;
373 case 'C':
374 *q++ = '(';
375 break;
376 case 'D':
377 GetDateFormatW(LOCALE_USER_DEFAULT, DATE_SHORTDATE, NULL, NULL, q, MAX_PATH - (q - out_string));
378 while (*q) q++;
379 break;
380 case 'E':
381 *q++ = '\x1b';
382 break;
383 case 'F':
384 *q++ = ')';
385 break;
386 case 'G':
387 *q++ = '>';
388 break;
389 case 'H':
390 *q++ = '\b';
391 break;
392 case 'L':
393 *q++ = '<';
394 break;
395 case 'N':
396 status = GetCurrentDirectoryW(ARRAY_SIZE(curdir), curdir);
397 if (status) {
398 *q++ = curdir[0];
400 break;
401 case 'P':
402 status = GetCurrentDirectoryW(ARRAY_SIZE(curdir), curdir);
403 if (status) {
404 strcatW (q, curdir);
405 while (*q) q++;
407 break;
408 case 'Q':
409 *q++ = '=';
410 break;
411 case 'S':
412 *q++ = ' ';
413 break;
414 case 'T':
415 GetTimeFormatW(LOCALE_USER_DEFAULT, 0, NULL, NULL, q, MAX_PATH);
416 while (*q) q++;
417 break;
418 case 'V':
419 strcatW (q, version_string);
420 while (*q) q++;
421 break;
422 case '_':
423 *q++ = '\n';
424 break;
425 case '+':
426 if (pushd_directories) {
427 memset(q, '+', pushd_directories->u.stackdepth);
428 q = q + pushd_directories->u.stackdepth;
430 break;
432 p++;
433 *q = '\0';
436 WCMD_output_asis (out_string);
439 void *heap_alloc(size_t size)
441 void *ret;
443 ret = HeapAlloc(GetProcessHeap(), 0, size);
444 if(!ret) {
445 ERR("Out of memory\n");
446 ExitProcess(1);
449 return ret;
452 /*************************************************************************
453 * WCMD_strsubstW
454 * Replaces a portion of a Unicode string with the specified string.
455 * It's up to the caller to ensure there is enough space in the
456 * destination buffer.
458 void WCMD_strsubstW(WCHAR *start, const WCHAR *next, const WCHAR *insert, int len) {
460 if (len < 0)
461 len=insert ? lstrlenW(insert) : 0;
462 if (start+len != next)
463 memmove(start+len, next, (strlenW(next) + 1) * sizeof(*next));
464 if (insert)
465 memcpy(start, insert, len * sizeof(*insert));
468 /***************************************************************************
469 * WCMD_skip_leading_spaces
471 * Return a pointer to the first non-whitespace character of string.
472 * Does not modify the input string.
474 WCHAR *WCMD_skip_leading_spaces (WCHAR *string) {
476 WCHAR *ptr;
478 ptr = string;
479 while (*ptr == ' ' || *ptr == '\t') ptr++;
480 return ptr;
483 /***************************************************************************
484 * WCMD_keyword_ws_found
486 * Checks if the string located at ptr matches a keyword (of length len)
487 * followed by a whitespace character (space or tab)
489 BOOL WCMD_keyword_ws_found(const WCHAR *keyword, int len, const WCHAR *ptr) {
490 return (CompareStringW(LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
491 ptr, len, keyword, len) == CSTR_EQUAL)
492 && ((*(ptr + len) == ' ') || (*(ptr + len) == '\t'));
495 /*************************************************************************
496 * WCMD_strip_quotes
498 * Remove first and last quote WCHARacters, preserving all other text
499 * Returns the location of the final quote
501 WCHAR *WCMD_strip_quotes(WCHAR *cmd) {
502 WCHAR *src = cmd + 1, *dest = cmd, *lastq = NULL, *lastquote;
503 while((*dest=*src) != '\0') {
504 if (*src=='\"')
505 lastq=dest;
506 dest++, src++;
508 lastquote = lastq;
509 if (lastq) {
510 dest=lastq++;
511 while ((*dest++=*lastq++) != 0)
514 return lastquote;
518 /*************************************************************************
519 * WCMD_is_magic_envvar
520 * Return TRUE if s is '%'magicvar'%'
521 * and is not masked by a real environment variable.
524 static inline BOOL WCMD_is_magic_envvar(const WCHAR *s, const WCHAR *magicvar)
526 int len;
528 if (s[0] != '%')
529 return FALSE; /* Didn't begin with % */
530 len = strlenW(s);
531 if (len < 2 || s[len-1] != '%')
532 return FALSE; /* Didn't end with another % */
534 if (CompareStringW(LOCALE_USER_DEFAULT,
535 NORM_IGNORECASE | SORT_STRINGSORT,
536 s+1, len-2, magicvar, -1) != CSTR_EQUAL) {
537 /* Name doesn't match. */
538 return FALSE;
541 if (GetEnvironmentVariableW(magicvar, NULL, 0) > 0) {
542 /* Masked by real environment variable. */
543 return FALSE;
546 return TRUE;
549 /*************************************************************************
550 * WCMD_expand_envvar
552 * Expands environment variables, allowing for WCHARacter substitution
554 static WCHAR *WCMD_expand_envvar(WCHAR *start, WCHAR startchar)
556 WCHAR *endOfVar = NULL, *s;
557 WCHAR *colonpos = NULL;
558 WCHAR thisVar[MAXSTRING];
559 WCHAR thisVarContents[MAXSTRING];
560 WCHAR savedchar = 0x00;
561 int len;
563 static const WCHAR ErrorLvl[] = {'E','R','R','O','R','L','E','V','E','L','\0'};
564 static const WCHAR Date[] = {'D','A','T','E','\0'};
565 static const WCHAR Time[] = {'T','I','M','E','\0'};
566 static const WCHAR Cd[] = {'C','D','\0'};
567 static const WCHAR Random[] = {'R','A','N','D','O','M','\0'};
568 WCHAR Delims[] = {'%',':','\0'}; /* First char gets replaced appropriately */
570 WINE_TRACE("Expanding: %s (%c)\n", wine_dbgstr_w(start), startchar);
572 /* Find the end of the environment variable, and extract name */
573 Delims[0] = startchar;
574 endOfVar = strpbrkW(start+1, Delims);
576 if (endOfVar == NULL || *endOfVar==' ') {
578 /* In batch program, missing terminator for % and no following
579 ':' just removes the '%' */
580 if (context) {
581 WCMD_strsubstW(start, start + 1, NULL, 0);
582 return start;
583 } else {
585 /* In command processing, just ignore it - allows command line
586 syntax like: for %i in (a.a) do echo %i */
587 return start+1;
591 /* If ':' found, process remaining up until '%' (or stop at ':' if
592 a missing '%' */
593 if (*endOfVar==':') {
594 WCHAR *endOfVar2 = strchrW(endOfVar+1, startchar);
595 if (endOfVar2 != NULL) endOfVar = endOfVar2;
598 memcpy(thisVar, start, ((endOfVar - start) + 1) * sizeof(WCHAR));
599 thisVar[(endOfVar - start)+1] = 0x00;
600 colonpos = strchrW(thisVar+1, ':');
602 /* If there's complex substitution, just need %var% for now
603 to get the expanded data to play with */
604 if (colonpos) {
605 *colonpos = startchar;
606 savedchar = *(colonpos+1);
607 *(colonpos+1) = 0x00;
610 /* By now, we know the variable we want to expand but it may be
611 surrounded by '!' if we are in delayed expansion - if so convert
612 to % signs. */
613 if (startchar=='!') {
614 thisVar[0] = '%';
615 thisVar[(endOfVar - start)] = '%';
617 WINE_TRACE("Retrieving contents of %s\n", wine_dbgstr_w(thisVar));
619 /* Expand to contents, if unchanged, return */
620 /* Handle DATE, TIME, ERRORLEVEL and CD replacements allowing */
621 /* override if existing env var called that name */
622 if (WCMD_is_magic_envvar(thisVar, ErrorLvl)) {
623 static const WCHAR fmt[] = {'%','d','\0'};
624 wsprintfW(thisVarContents, fmt, errorlevel);
625 len = strlenW(thisVarContents);
626 } else if (WCMD_is_magic_envvar(thisVar, Date)) {
627 GetDateFormatW(LOCALE_USER_DEFAULT, DATE_SHORTDATE, NULL,
628 NULL, thisVarContents, MAXSTRING);
629 len = strlenW(thisVarContents);
630 } else if (WCMD_is_magic_envvar(thisVar, Time)) {
631 GetTimeFormatW(LOCALE_USER_DEFAULT, TIME_NOSECONDS, NULL,
632 NULL, thisVarContents, MAXSTRING);
633 len = strlenW(thisVarContents);
634 } else if (WCMD_is_magic_envvar(thisVar, Cd)) {
635 GetCurrentDirectoryW(MAXSTRING, thisVarContents);
636 len = strlenW(thisVarContents);
637 } else if (WCMD_is_magic_envvar(thisVar, Random)) {
638 static const WCHAR fmt[] = {'%','d','\0'};
639 wsprintfW(thisVarContents, fmt, rand() % 32768);
640 len = strlenW(thisVarContents);
641 } else {
643 len = ExpandEnvironmentStringsW(thisVar, thisVarContents, ARRAY_SIZE(thisVarContents));
646 if (len == 0)
647 return endOfVar+1;
649 /* In a batch program, unknown env vars are replaced with nothing,
650 note syntax %garbage:1,3% results in anything after the ':'
651 except the %
652 From the command line, you just get back what you entered */
653 if (lstrcmpiW(thisVar, thisVarContents) == 0) {
655 /* Restore the complex part after the compare */
656 if (colonpos) {
657 *colonpos = ':';
658 *(colonpos+1) = savedchar;
661 /* Command line - just ignore this */
662 if (context == NULL) return endOfVar+1;
665 /* Batch - replace unknown env var with nothing */
666 if (colonpos == NULL) {
667 WCMD_strsubstW(start, endOfVar + 1, NULL, 0);
668 } else {
669 len = strlenW(thisVar);
670 thisVar[len-1] = 0x00;
671 /* If %:...% supplied, : is retained */
672 if (colonpos == thisVar+1) {
673 WCMD_strsubstW(start, endOfVar + 1, colonpos, -1);
674 } else {
675 WCMD_strsubstW(start, endOfVar + 1, colonpos + 1, -1);
678 return start;
682 /* See if we need to do complex substitution (any ':'s), if not
683 then our work here is done */
684 if (colonpos == NULL) {
685 WCMD_strsubstW(start, endOfVar + 1, thisVarContents, -1);
686 return start;
689 /* Restore complex bit */
690 *colonpos = ':';
691 *(colonpos+1) = savedchar;
694 Handle complex substitutions:
695 xxx=yyy (replace xxx with yyy)
696 *xxx=yyy (replace up to and including xxx with yyy)
697 ~x (from x WCHARs in)
698 ~-x (from x WCHARs from the end)
699 ~x,y (from x WCHARs in for y WCHARacters)
700 ~x,-y (from x WCHARs in until y WCHARacters from the end)
703 /* ~ is substring manipulation */
704 if (savedchar == '~') {
706 int substrposition, substrlength = 0;
707 WCHAR *commapos = strchrW(colonpos+2, ',');
708 WCHAR *startCopy;
710 substrposition = atolW(colonpos+2);
711 if (commapos) substrlength = atolW(commapos+1);
713 /* Check bounds */
714 if (substrposition >= 0) {
715 startCopy = &thisVarContents[min(substrposition, len)];
716 } else {
717 startCopy = &thisVarContents[max(0, len+substrposition-1)];
720 if (commapos == NULL) {
721 /* Copy the lot */
722 WCMD_strsubstW(start, endOfVar + 1, startCopy, -1);
723 } else if (substrlength < 0) {
725 int copybytes = (len+substrlength-1)-(startCopy-thisVarContents);
726 if (copybytes > len) copybytes = len;
727 else if (copybytes < 0) copybytes = 0;
728 WCMD_strsubstW(start, endOfVar + 1, startCopy, copybytes);
729 } else {
730 substrlength = min(substrlength, len - (startCopy- thisVarContents + 1));
731 WCMD_strsubstW(start, endOfVar + 1, startCopy, substrlength);
734 /* search and replace manipulation */
735 } else {
736 WCHAR *equalspos = strstrW(colonpos, equalW);
737 WCHAR *replacewith = equalspos+1;
738 WCHAR *found = NULL;
739 WCHAR *searchIn;
740 WCHAR *searchFor;
742 if (equalspos == NULL) return start+1;
743 s = heap_strdupW(endOfVar + 1);
745 /* Null terminate both strings */
746 thisVar[strlenW(thisVar)-1] = 0x00;
747 *equalspos = 0x00;
749 /* Since we need to be case insensitive, copy the 2 buffers */
750 searchIn = heap_strdupW(thisVarContents);
751 CharUpperBuffW(searchIn, strlenW(thisVarContents));
752 searchFor = heap_strdupW(colonpos+1);
753 CharUpperBuffW(searchFor, strlenW(colonpos+1));
755 /* Handle wildcard case */
756 if (*(colonpos+1) == '*') {
757 /* Search for string to replace */
758 found = strstrW(searchIn, searchFor+1);
760 if (found) {
761 /* Do replacement */
762 strcpyW(start, replacewith);
763 strcatW(start, thisVarContents + (found-searchIn) + strlenW(searchFor+1));
764 strcatW(start, s);
765 } else {
766 /* Copy as is */
767 strcpyW(start, thisVarContents);
768 strcatW(start, s);
771 } else {
772 /* Loop replacing all instances */
773 WCHAR *lastFound = searchIn;
774 WCHAR *outputposn = start;
776 *start = 0x00;
777 while ((found = strstrW(lastFound, searchFor))) {
778 lstrcpynW(outputposn,
779 thisVarContents + (lastFound-searchIn),
780 (found - lastFound)+1);
781 outputposn = outputposn + (found - lastFound);
782 strcatW(outputposn, replacewith);
783 outputposn = outputposn + strlenW(replacewith);
784 lastFound = found + strlenW(searchFor);
786 strcatW(outputposn,
787 thisVarContents + (lastFound-searchIn));
788 strcatW(outputposn, s);
790 heap_free(s);
791 heap_free(searchIn);
792 heap_free(searchFor);
794 return start;
797 /*****************************************************************************
798 * Expand the command. Native expands lines from batch programs as they are
799 * read in and not again, except for 'for' variable substitution.
800 * eg. As evidence, "echo %1 && shift && echo %1" or "echo %%path%%"
801 * atExecute is TRUE when the expansion is occurring as the command is executed
802 * rather than at parse time, i.e. delayed expansion and for loops need to be
803 * processed
805 static void handleExpansion(WCHAR *cmd, BOOL atExecute, BOOL delayed) {
807 /* For commands in a context (batch program): */
808 /* Expand environment variables in a batch file %{0-9} first */
809 /* including support for any ~ modifiers */
810 /* Additionally: */
811 /* Expand the DATE, TIME, CD, RANDOM and ERRORLEVEL special */
812 /* names allowing environment variable overrides */
813 /* NOTE: To support the %PATH:xxx% syntax, also perform */
814 /* manual expansion of environment variables here */
816 WCHAR *p = cmd;
817 WCHAR *t;
818 int i;
819 WCHAR *delayedp = NULL;
820 WCHAR startchar = '%';
821 WCHAR *normalp;
823 /* Display the FOR variables in effect */
824 for (i=0;i<52;i++) {
825 if (forloopcontext.variable[i]) {
826 WINE_TRACE("FOR variable context: %c = '%s'\n",
827 i<26?i+'a':(i-26)+'A',
828 wine_dbgstr_w(forloopcontext.variable[i]));
832 /* Find the next environment variable delimiter */
833 normalp = strchrW(p, '%');
834 if (delayed) delayedp = strchrW(p, '!');
835 if (!normalp) p = delayedp;
836 else if (!delayedp) p = normalp;
837 else p = min(p,delayedp);
838 if (p) startchar = *p;
840 while (p) {
842 WINE_TRACE("Translate command:%s %d (at: %s)\n",
843 wine_dbgstr_w(cmd), atExecute, wine_dbgstr_w(p));
844 i = *(p+1) - '0';
846 /* Don't touch %% unless it's in Batch */
847 if (!atExecute && *(p+1) == startchar) {
848 if (context) {
849 WCMD_strsubstW(p, p+1, NULL, 0);
851 p+=1;
853 /* Replace %~ modifications if in batch program */
854 } else if (*(p+1) == '~') {
855 WCMD_HandleTildaModifiers(&p, atExecute);
856 p++;
858 /* Replace use of %0...%9 if in batch program*/
859 } else if (!atExecute && context && (i >= 0) && (i <= 9) && startchar == '%') {
860 t = WCMD_parameter(context -> command, i + context -> shift_count[i],
861 NULL, TRUE, TRUE);
862 WCMD_strsubstW(p, p+2, t, -1);
864 /* Replace use of %* if in batch program*/
865 } else if (!atExecute && context && *(p+1)=='*' && startchar == '%') {
866 WCHAR *startOfParms = NULL;
867 WCHAR *thisParm = WCMD_parameter(context -> command, 0, &startOfParms, TRUE, TRUE);
868 if (startOfParms != NULL) {
869 startOfParms += strlenW(thisParm);
870 while (*startOfParms==' ' || *startOfParms == '\t') startOfParms++;
871 WCMD_strsubstW(p, p+2, startOfParms, -1);
872 } else
873 WCMD_strsubstW(p, p+2, NULL, 0);
875 } else {
876 int forvaridx = FOR_VAR_IDX(*(p+1));
877 if (startchar == '%' && forvaridx != -1 && forloopcontext.variable[forvaridx]) {
878 /* Replace the 2 characters, % and for variable character */
879 WCMD_strsubstW(p, p + 2, forloopcontext.variable[forvaridx], -1);
880 } else if (!atExecute || startchar == '!') {
881 p = WCMD_expand_envvar(p, startchar);
883 /* In a FOR loop, see if this is the variable to replace */
884 } else { /* Ignore %'s on second pass of batch program */
885 p++;
889 /* Find the next environment variable delimiter */
890 normalp = strchrW(p, '%');
891 if (delayed) delayedp = strchrW(p, '!');
892 if (!normalp) p = delayedp;
893 else if (!delayedp) p = normalp;
894 else p = min(p,delayedp);
895 if (p) startchar = *p;
898 return;
902 /*******************************************************************
903 * WCMD_parse - parse a command into parameters and qualifiers.
905 * On exit, all qualifiers are concatenated into q, the first string
906 * not beginning with "/" is in p1 and the
907 * second in p2. Any subsequent non-qualifier strings are lost.
908 * Parameters in quotes are handled.
910 static void WCMD_parse (const WCHAR *s, WCHAR *q, WCHAR *p1, WCHAR *p2)
912 int p = 0;
914 *q = *p1 = *p2 = '\0';
915 while (TRUE) {
916 switch (*s) {
917 case '/':
918 *q++ = *s++;
919 while ((*s != '\0') && (*s != ' ') && *s != '/') {
920 *q++ = toupperW (*s++);
922 *q = '\0';
923 break;
924 case ' ':
925 case '\t':
926 s++;
927 break;
928 case '"':
929 s++;
930 while ((*s != '\0') && (*s != '"')) {
931 if (p == 0) *p1++ = *s++;
932 else if (p == 1) *p2++ = *s++;
933 else s++;
935 if (p == 0) *p1 = '\0';
936 if (p == 1) *p2 = '\0';
937 p++;
938 if (*s == '"') s++;
939 break;
940 case '\0':
941 return;
942 default:
943 while ((*s != '\0') && (*s != ' ') && (*s != '\t')
944 && (*s != '=') && (*s != ',') ) {
945 if (p == 0) *p1++ = *s++;
946 else if (p == 1) *p2++ = *s++;
947 else s++;
949 /* Skip concurrent parms */
950 while ((*s == ' ') || (*s == '\t') || (*s == '=') || (*s == ',') ) s++;
952 if (p == 0) *p1 = '\0';
953 if (p == 1) *p2 = '\0';
954 p++;
959 static void init_msvcrt_io_block(STARTUPINFOW* st)
961 STARTUPINFOW st_p;
962 /* fetch the parent MSVCRT info block if any, so that the child can use the
963 * same handles as its grand-father
965 st_p.cb = sizeof(STARTUPINFOW);
966 GetStartupInfoW(&st_p);
967 st->cbReserved2 = st_p.cbReserved2;
968 st->lpReserved2 = st_p.lpReserved2;
969 if (st_p.cbReserved2 && st_p.lpReserved2)
971 unsigned num = *(unsigned*)st_p.lpReserved2;
972 char* flags;
973 HANDLE* handles;
974 BYTE *ptr;
975 size_t sz;
977 /* Override the entries for fd 0,1,2 if we happened
978 * to change those std handles (this depends on the way cmd sets
979 * its new input & output handles)
981 sz = max(sizeof(unsigned) + (sizeof(char) + sizeof(HANDLE)) * 3, st_p.cbReserved2);
982 ptr = heap_alloc(sz);
983 flags = (char*)(ptr + sizeof(unsigned));
984 handles = (HANDLE*)(flags + num * sizeof(char));
986 memcpy(ptr, st_p.lpReserved2, st_p.cbReserved2);
987 st->cbReserved2 = sz;
988 st->lpReserved2 = ptr;
990 #define WX_OPEN 0x01 /* see dlls/msvcrt/file.c */
991 if (num <= 0 || (flags[0] & WX_OPEN))
993 handles[0] = GetStdHandle(STD_INPUT_HANDLE);
994 flags[0] |= WX_OPEN;
996 if (num <= 1 || (flags[1] & WX_OPEN))
998 handles[1] = GetStdHandle(STD_OUTPUT_HANDLE);
999 flags[1] |= WX_OPEN;
1001 if (num <= 2 || (flags[2] & WX_OPEN))
1003 handles[2] = GetStdHandle(STD_ERROR_HANDLE);
1004 flags[2] |= WX_OPEN;
1006 #undef WX_OPEN
1010 /******************************************************************************
1011 * WCMD_run_program
1013 * Execute a command line as an external program. Must allow recursion.
1015 * Precedence:
1016 * Manual testing under windows shows PATHEXT plays a key part in this,
1017 * and the search algorithm and precedence appears to be as follows.
1019 * Search locations:
1020 * If directory supplied on command, just use that directory
1021 * If extension supplied on command, look for that explicit name first
1022 * Otherwise, search in each directory on the path
1023 * Precedence:
1024 * If extension supplied on command, look for that explicit name first
1025 * Then look for supplied name .* (even if extension supplied, so
1026 * 'garbage.exe' will match 'garbage.exe.cmd')
1027 * If any found, cycle through PATHEXT looking for name.exe one by one
1028 * Launching
1029 * Once a match has been found, it is launched - Code currently uses
1030 * findexecutable to achieve this which is left untouched.
1031 * If an executable has not been found, and we were launched through
1032 * a call, we need to check if the command is an internal command,
1033 * so go back through wcmd_execute.
1036 void WCMD_run_program (WCHAR *command, BOOL called)
1038 WCHAR temp[MAX_PATH];
1039 WCHAR pathtosearch[MAXSTRING];
1040 WCHAR *pathposn;
1041 WCHAR stemofsearch[MAX_PATH]; /* maximum allowed executable name is
1042 MAX_PATH, including null character */
1043 WCHAR *lastSlash;
1044 WCHAR pathext[MAXSTRING];
1045 WCHAR *firstParam;
1046 BOOL extensionsupplied = FALSE;
1047 BOOL status;
1048 DWORD len;
1049 static const WCHAR envPath[] = {'P','A','T','H','\0'};
1050 static const WCHAR delims[] = {'/','\\',':','\0'};
1052 /* Quick way to get the filename is to extract the first argument. */
1053 WINE_TRACE("Running '%s' (%d)\n", wine_dbgstr_w(command), called);
1054 firstParam = WCMD_parameter(command, 0, NULL, FALSE, TRUE);
1055 if (!firstParam) return;
1057 /* Calculate the search path and stem to search for */
1058 if (strpbrkW (firstParam, delims) == NULL) { /* No explicit path given, search path */
1059 static const WCHAR curDir[] = {'.',';','\0'};
1060 strcpyW(pathtosearch, curDir);
1061 len = GetEnvironmentVariableW(envPath, &pathtosearch[2], ARRAY_SIZE(pathtosearch)-2);
1062 if ((len == 0) || (len >= ARRAY_SIZE(pathtosearch) - 2)) {
1063 static const WCHAR curDir[] = {'.','\0'};
1064 strcpyW (pathtosearch, curDir);
1066 if (strchrW(firstParam, '.') != NULL) extensionsupplied = TRUE;
1067 if (strlenW(firstParam) >= MAX_PATH)
1069 WCMD_output_asis_stderr(WCMD_LoadMessage(WCMD_LINETOOLONG));
1070 return;
1073 strcpyW(stemofsearch, firstParam);
1075 } else {
1077 /* Convert eg. ..\fred to include a directory by removing file part */
1078 GetFullPathNameW(firstParam, ARRAY_SIZE(pathtosearch), pathtosearch, NULL);
1079 lastSlash = strrchrW(pathtosearch, '\\');
1080 if (lastSlash && strchrW(lastSlash, '.') != NULL) extensionsupplied = TRUE;
1081 strcpyW(stemofsearch, lastSlash+1);
1083 /* Reduce pathtosearch to a path with trailing '\' to support c:\a.bat and
1084 c:\windows\a.bat syntax */
1085 if (lastSlash) *(lastSlash + 1) = 0x00;
1088 /* Now extract PATHEXT */
1089 len = GetEnvironmentVariableW(envPathExt, pathext, ARRAY_SIZE(pathext));
1090 if ((len == 0) || (len >= ARRAY_SIZE(pathext))) {
1091 strcpyW (pathext, dfltPathExt);
1094 /* Loop through the search path, dir by dir */
1095 pathposn = pathtosearch;
1096 WINE_TRACE("Searching in '%s' for '%s'\n", wine_dbgstr_w(pathtosearch),
1097 wine_dbgstr_w(stemofsearch));
1098 while (pathposn) {
1099 WCHAR thisDir[MAX_PATH] = {'\0'};
1100 int length = 0;
1101 WCHAR *pos = NULL;
1102 BOOL found = FALSE;
1103 BOOL inside_quotes = FALSE;
1105 /* Work on the first directory on the search path */
1106 pos = pathposn;
1107 while ((inside_quotes || *pos != ';') && *pos != 0)
1109 if (*pos == '"')
1110 inside_quotes = !inside_quotes;
1111 pos++;
1114 if (*pos) { /* Reached semicolon */
1115 memcpy(thisDir, pathposn, (pos-pathposn) * sizeof(WCHAR));
1116 thisDir[(pos-pathposn)] = 0x00;
1117 pathposn = pos+1;
1118 } else { /* Reached string end */
1119 strcpyW(thisDir, pathposn);
1120 pathposn = NULL;
1123 /* Remove quotes */
1124 length = strlenW(thisDir);
1125 if (thisDir[length - 1] == '"')
1126 thisDir[length - 1] = 0;
1128 if (*thisDir != '"')
1129 strcpyW(temp, thisDir);
1130 else
1131 strcpyW(temp, thisDir + 1);
1133 /* Since you can have eg. ..\.. on the path, need to expand
1134 to full information */
1135 GetFullPathNameW(temp, MAX_PATH, thisDir, NULL);
1137 /* 1. If extension supplied, see if that file exists */
1138 strcatW(thisDir, slashW);
1139 strcatW(thisDir, stemofsearch);
1140 pos = &thisDir[strlenW(thisDir)]; /* Pos = end of name */
1142 /* 1. If extension supplied, see if that file exists */
1143 if (extensionsupplied) {
1144 if (GetFileAttributesW(thisDir) != INVALID_FILE_ATTRIBUTES) {
1145 found = TRUE;
1149 /* 2. Any .* matches? */
1150 if (!found) {
1151 HANDLE h;
1152 WIN32_FIND_DATAW finddata;
1153 static const WCHAR allFiles[] = {'.','*','\0'};
1155 strcatW(thisDir,allFiles);
1156 h = FindFirstFileW(thisDir, &finddata);
1157 FindClose(h);
1158 if (h != INVALID_HANDLE_VALUE) {
1160 WCHAR *thisExt = pathext;
1162 /* 3. Yes - Try each path ext */
1163 while (thisExt) {
1164 WCHAR *nextExt = strchrW(thisExt, ';');
1166 if (nextExt) {
1167 memcpy(pos, thisExt, (nextExt-thisExt) * sizeof(WCHAR));
1168 pos[(nextExt-thisExt)] = 0x00;
1169 thisExt = nextExt+1;
1170 } else {
1171 strcpyW(pos, thisExt);
1172 thisExt = NULL;
1175 if (GetFileAttributesW(thisDir) != INVALID_FILE_ATTRIBUTES) {
1176 found = TRUE;
1177 thisExt = NULL;
1183 /* Once found, launch it */
1184 if (found) {
1185 STARTUPINFOW st;
1186 PROCESS_INFORMATION pe;
1187 SHFILEINFOW psfi;
1188 DWORD console;
1189 HINSTANCE hinst;
1190 WCHAR *ext = strrchrW( thisDir, '.' );
1191 static const WCHAR batExt[] = {'.','b','a','t','\0'};
1192 static const WCHAR cmdExt[] = {'.','c','m','d','\0'};
1194 WINE_TRACE("Found as %s\n", wine_dbgstr_w(thisDir));
1196 /* Special case BAT and CMD */
1197 if (ext && (!strcmpiW(ext, batExt) || !strcmpiW(ext, cmdExt))) {
1198 BOOL oldinteractive = interactive;
1199 interactive = FALSE;
1200 WCMD_batch (thisDir, command, called, NULL, INVALID_HANDLE_VALUE);
1201 interactive = oldinteractive;
1202 return;
1203 } else {
1205 /* thisDir contains the file to be launched, but with what?
1206 eg. a.exe will require a.exe to be launched, a.html may be iexplore */
1207 hinst = FindExecutableW (thisDir, NULL, temp);
1208 if ((INT_PTR)hinst < 32)
1209 console = 0;
1210 else
1211 console = SHGetFileInfoW(temp, 0, &psfi, sizeof(psfi), SHGFI_EXETYPE);
1213 ZeroMemory (&st, sizeof(STARTUPINFOW));
1214 st.cb = sizeof(STARTUPINFOW);
1215 init_msvcrt_io_block(&st);
1217 /* Launch the process and if a CUI wait on it to complete
1218 Note: Launching internal wine processes cannot specify a full path to exe */
1219 status = CreateProcessW(thisDir,
1220 command, NULL, NULL, TRUE, 0, NULL, NULL, &st, &pe);
1221 heap_free(st.lpReserved2);
1222 if ((opt_c || opt_k) && !opt_s && !status
1223 && GetLastError()==ERROR_FILE_NOT_FOUND && command[0]=='\"') {
1224 /* strip first and last quote WCHARacters and try again */
1225 WCMD_strip_quotes(command);
1226 opt_s = TRUE;
1227 WCMD_run_program(command, called);
1228 return;
1231 if (!status)
1232 break;
1234 /* Always wait when non-interactive (cmd /c or in batch program),
1235 or for console applications */
1236 if (!interactive || (console && !HIWORD(console)))
1237 WaitForSingleObject (pe.hProcess, INFINITE);
1238 GetExitCodeProcess (pe.hProcess, &errorlevel);
1239 if (errorlevel == STILL_ACTIVE) errorlevel = 0;
1241 CloseHandle(pe.hProcess);
1242 CloseHandle(pe.hThread);
1243 return;
1248 /* Not found anywhere - were we called? */
1249 if (called) {
1250 CMD_LIST *toExecute = NULL; /* Commands left to be executed */
1252 /* Parse the command string, without reading any more input */
1253 WCMD_ReadAndParseLine(command, &toExecute, INVALID_HANDLE_VALUE);
1254 WCMD_process_commands(toExecute, FALSE, called);
1255 WCMD_free_commands(toExecute);
1256 toExecute = NULL;
1257 return;
1260 /* Not found anywhere - give up */
1261 WCMD_output_stderr(WCMD_LoadMessage(WCMD_NO_COMMAND_FOUND), command);
1263 /* If a command fails to launch, it sets errorlevel 9009 - which
1264 does not seem to have any associated constant definition */
1265 errorlevel = 9009;
1266 return;
1270 /*****************************************************************************
1271 * Process one command. If the command is EXIT this routine does not return.
1272 * We will recurse through here executing batch files.
1273 * Note: If call is used to a non-existing program, we reparse the line and
1274 * try to run it as an internal command. 'retrycall' represents whether
1275 * we are attempting this retry.
1277 void WCMD_execute (const WCHAR *command, const WCHAR *redirects,
1278 CMD_LIST **cmdList, BOOL retrycall)
1280 WCHAR *cmd, *p, *redir;
1281 int status, i;
1282 DWORD count, creationDisposition;
1283 HANDLE h;
1284 WCHAR *whichcmd;
1285 SECURITY_ATTRIBUTES sa;
1286 WCHAR *new_cmd = NULL;
1287 WCHAR *new_redir = NULL;
1288 HANDLE old_stdhandles[3] = {GetStdHandle (STD_INPUT_HANDLE),
1289 GetStdHandle (STD_OUTPUT_HANDLE),
1290 GetStdHandle (STD_ERROR_HANDLE)};
1291 DWORD idx_stdhandles[3] = {STD_INPUT_HANDLE,
1292 STD_OUTPUT_HANDLE,
1293 STD_ERROR_HANDLE};
1294 BOOL prev_echo_mode, piped = FALSE;
1296 WINE_TRACE("command on entry:%s (%p)\n",
1297 wine_dbgstr_w(command), cmdList);
1299 /* If the next command is a pipe then we implement pipes by redirecting
1300 the output from this command to a temp file and input into the
1301 next command from that temp file.
1302 FIXME: Use of named pipes would make more sense here as currently this
1303 process has to finish before the next one can start but this requires
1304 a change to not wait for the first app to finish but rather the pipe */
1305 if (cmdList && (*cmdList)->nextcommand &&
1306 (*cmdList)->nextcommand->prevDelim == CMD_PIPE) {
1308 WCHAR temp_path[MAX_PATH];
1309 static const WCHAR cmdW[] = {'C','M','D','\0'};
1311 /* Remember piping is in action */
1312 WINE_TRACE("Output needs to be piped\n");
1313 piped = TRUE;
1315 /* Generate a unique temporary filename */
1316 GetTempPathW(ARRAY_SIZE(temp_path), temp_path);
1317 GetTempFileNameW(temp_path, cmdW, 0, (*cmdList)->nextcommand->pipeFile);
1318 WINE_TRACE("Using temporary file of %s\n",
1319 wine_dbgstr_w((*cmdList)->nextcommand->pipeFile));
1322 /* Move copy of the command onto the heap so it can be expanded */
1323 new_cmd = heap_alloc(MAXSTRING * sizeof(WCHAR));
1324 strcpyW(new_cmd, command);
1326 /* Move copy of the redirects onto the heap so it can be expanded */
1327 new_redir = heap_alloc(MAXSTRING * sizeof(WCHAR));
1329 /* If piped output, send stdout to the pipe by appending >filename to redirects */
1330 if (piped) {
1331 static const WCHAR redirOut[] = {'%','s',' ','>',' ','%','s','\0'};
1332 wsprintfW (new_redir, redirOut, redirects, (*cmdList)->nextcommand->pipeFile);
1333 WINE_TRACE("Redirects now %s\n", wine_dbgstr_w(new_redir));
1334 } else {
1335 strcpyW(new_redir, redirects);
1338 /* Expand variables in command line mode only (batch mode will
1339 be expanded as the line is read in, except for 'for' loops) */
1340 handleExpansion(new_cmd, (context != NULL), delayedsubst);
1341 handleExpansion(new_redir, (context != NULL), delayedsubst);
1342 cmd = new_cmd;
1345 * Changing default drive has to be handled as a special case, anything
1346 * else if it exists after whitespace is ignored
1349 if ((cmd[1] == ':') && IsCharAlphaW(cmd[0]) &&
1350 (!cmd[2] || cmd[2] == ' ' || cmd[2] == '\t')) {
1351 WCHAR envvar[5];
1352 WCHAR dir[MAX_PATH];
1354 /* Ignore potential garbage on the same line */
1355 cmd[2]=0x00;
1357 /* According to MSDN CreateProcess docs, special env vars record
1358 the current directory on each drive, in the form =C:
1359 so see if one specified, and if so go back to it */
1360 strcpyW(envvar, equalW);
1361 strcatW(envvar, cmd);
1362 if (GetEnvironmentVariableW(envvar, dir, MAX_PATH) == 0) {
1363 static const WCHAR fmt[] = {'%','s','\\','\0'};
1364 wsprintfW(cmd, fmt, cmd);
1365 WINE_TRACE("No special directory settings, using dir of %s\n", wine_dbgstr_w(cmd));
1367 WINE_TRACE("Got directory %s as %s\n", wine_dbgstr_w(envvar), wine_dbgstr_w(cmd));
1368 status = SetCurrentDirectoryW(cmd);
1369 if (!status) WCMD_print_error ();
1370 heap_free(cmd );
1371 heap_free(new_redir);
1372 return;
1375 sa.nLength = sizeof(sa);
1376 sa.lpSecurityDescriptor = NULL;
1377 sa.bInheritHandle = TRUE;
1380 * Redirect stdin, stdout and/or stderr if required.
1383 /* STDIN could come from a preceding pipe, so delete on close if it does */
1384 if (cmdList && (*cmdList)->pipeFile[0] != 0x00) {
1385 WINE_TRACE("Input coming from %s\n", wine_dbgstr_w((*cmdList)->pipeFile));
1386 h = CreateFileW((*cmdList)->pipeFile, GENERIC_READ,
1387 FILE_SHARE_READ | FILE_SHARE_WRITE, &sa, OPEN_EXISTING,
1388 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE, NULL);
1389 if (h == INVALID_HANDLE_VALUE) {
1390 WCMD_print_error ();
1391 heap_free(cmd);
1392 heap_free(new_redir);
1393 return;
1395 SetStdHandle (STD_INPUT_HANDLE, h);
1397 /* No need to remember the temporary name any longer once opened */
1398 (*cmdList)->pipeFile[0] = 0x00;
1400 /* Otherwise STDIN could come from a '<' redirect */
1401 } else if ((p = strchrW(new_redir,'<')) != NULL) {
1402 h = CreateFileW(WCMD_parameter(++p, 0, NULL, FALSE, FALSE), GENERIC_READ, FILE_SHARE_READ,
1403 &sa, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
1404 if (h == INVALID_HANDLE_VALUE) {
1405 WCMD_print_error ();
1406 heap_free(cmd);
1407 heap_free(new_redir);
1408 return;
1410 SetStdHandle (STD_INPUT_HANDLE, h);
1413 /* Scan the whole command looking for > and 2> */
1414 redir = new_redir;
1415 while (redir != NULL && ((p = strchrW(redir,'>')) != NULL)) {
1416 int handle = 0;
1418 if (p > redir && (*(p-1)=='2'))
1419 handle = 2;
1420 else
1421 handle = 1;
1423 p++;
1424 if ('>' == *p) {
1425 creationDisposition = OPEN_ALWAYS;
1426 p++;
1428 else {
1429 creationDisposition = CREATE_ALWAYS;
1432 /* Add support for 2>&1 */
1433 redir = p;
1434 if (*p == '&') {
1435 int idx = *(p+1) - '0';
1437 if (DuplicateHandle(GetCurrentProcess(),
1438 GetStdHandle(idx_stdhandles[idx]),
1439 GetCurrentProcess(),
1441 0, TRUE, DUPLICATE_SAME_ACCESS) == 0) {
1442 WINE_FIXME("Duplicating handle failed with gle %d\n", GetLastError());
1444 WINE_TRACE("Redirect %d (%p) to %d (%p)\n", handle, GetStdHandle(idx_stdhandles[idx]), idx, h);
1446 } else {
1447 WCHAR *param = WCMD_parameter(p, 0, NULL, FALSE, FALSE);
1448 h = CreateFileW(param, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_DELETE,
1449 &sa, creationDisposition, FILE_ATTRIBUTE_NORMAL, NULL);
1450 if (h == INVALID_HANDLE_VALUE) {
1451 WCMD_print_error ();
1452 heap_free(cmd);
1453 heap_free(new_redir);
1454 return;
1456 if (SetFilePointer (h, 0, NULL, FILE_END) ==
1457 INVALID_SET_FILE_POINTER) {
1458 WCMD_print_error ();
1460 WINE_TRACE("Redirect %d to '%s' (%p)\n", handle, wine_dbgstr_w(param), h);
1463 SetStdHandle (idx_stdhandles[handle], h);
1467 * Strip leading whitespaces, and a '@' if supplied
1469 whichcmd = WCMD_skip_leading_spaces(cmd);
1470 WINE_TRACE("Command: '%s'\n", wine_dbgstr_w(cmd));
1471 if (whichcmd[0] == '@') whichcmd++;
1474 * Check if the command entered is internal. If it is, pass the rest of the
1475 * line down to the command. If not try to run a program.
1478 count = 0;
1479 while (IsCharAlphaNumericW(whichcmd[count])) {
1480 count++;
1482 for (i=0; i<=WCMD_EXIT; i++) {
1483 if (CompareStringW(LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
1484 whichcmd, count, inbuilt[i], -1) == CSTR_EQUAL) break;
1486 p = WCMD_skip_leading_spaces (&whichcmd[count]);
1487 WCMD_parse (p, quals, param1, param2);
1488 WINE_TRACE("param1: %s, param2: %s\n", wine_dbgstr_w(param1), wine_dbgstr_w(param2));
1490 if (i <= WCMD_EXIT && (p[0] == '/') && (p[1] == '?')) {
1491 /* this is a help request for a builtin program */
1492 i = WCMD_HELP;
1493 memcpy(p, whichcmd, count * sizeof(WCHAR));
1494 p[count] = '\0';
1498 switch (i) {
1500 case WCMD_CALL:
1501 WCMD_call (p);
1502 break;
1503 case WCMD_CD:
1504 case WCMD_CHDIR:
1505 WCMD_setshow_default (p);
1506 break;
1507 case WCMD_CLS:
1508 WCMD_clear_screen ();
1509 break;
1510 case WCMD_COPY:
1511 WCMD_copy (p);
1512 break;
1513 case WCMD_CTTY:
1514 WCMD_change_tty ();
1515 break;
1516 case WCMD_DATE:
1517 WCMD_setshow_date ();
1518 break;
1519 case WCMD_DEL:
1520 case WCMD_ERASE:
1521 WCMD_delete (p);
1522 break;
1523 case WCMD_DIR:
1524 WCMD_directory (p);
1525 break;
1526 case WCMD_ECHO:
1527 WCMD_echo(&whichcmd[count]);
1528 break;
1529 case WCMD_GOTO:
1530 WCMD_goto (cmdList);
1531 break;
1532 case WCMD_HELP:
1533 WCMD_give_help (p);
1534 break;
1535 case WCMD_LABEL:
1536 WCMD_volume (TRUE, p);
1537 break;
1538 case WCMD_MD:
1539 case WCMD_MKDIR:
1540 WCMD_create_dir (p);
1541 break;
1542 case WCMD_MOVE:
1543 WCMD_move ();
1544 break;
1545 case WCMD_PATH:
1546 WCMD_setshow_path (p);
1547 break;
1548 case WCMD_PAUSE:
1549 WCMD_pause ();
1550 break;
1551 case WCMD_PROMPT:
1552 WCMD_setshow_prompt ();
1553 break;
1554 case WCMD_REM:
1555 break;
1556 case WCMD_REN:
1557 case WCMD_RENAME:
1558 WCMD_rename ();
1559 break;
1560 case WCMD_RD:
1561 case WCMD_RMDIR:
1562 WCMD_remove_dir (p);
1563 break;
1564 case WCMD_SETLOCAL:
1565 WCMD_setlocal(p);
1566 break;
1567 case WCMD_ENDLOCAL:
1568 WCMD_endlocal();
1569 break;
1570 case WCMD_SET:
1571 WCMD_setshow_env (p);
1572 break;
1573 case WCMD_SHIFT:
1574 WCMD_shift (p);
1575 break;
1576 case WCMD_START:
1577 WCMD_start (p);
1578 break;
1579 case WCMD_TIME:
1580 WCMD_setshow_time ();
1581 break;
1582 case WCMD_TITLE:
1583 if (strlenW(&whichcmd[count]) > 0)
1584 WCMD_title(&whichcmd[count+1]);
1585 break;
1586 case WCMD_TYPE:
1587 WCMD_type (p);
1588 break;
1589 case WCMD_VER:
1590 WCMD_output_asis(newlineW);
1591 WCMD_version ();
1592 break;
1593 case WCMD_VERIFY:
1594 WCMD_verify (p);
1595 break;
1596 case WCMD_VOL:
1597 WCMD_volume (FALSE, p);
1598 break;
1599 case WCMD_PUSHD:
1600 WCMD_pushd(p);
1601 break;
1602 case WCMD_POPD:
1603 WCMD_popd();
1604 break;
1605 case WCMD_ASSOC:
1606 WCMD_assoc(p, TRUE);
1607 break;
1608 case WCMD_COLOR:
1609 WCMD_color();
1610 break;
1611 case WCMD_FTYPE:
1612 WCMD_assoc(p, FALSE);
1613 break;
1614 case WCMD_MORE:
1615 WCMD_more(p);
1616 break;
1617 case WCMD_CHOICE:
1618 WCMD_choice(p);
1619 break;
1620 case WCMD_MKLINK:
1621 WCMD_mklink(p);
1622 break;
1623 case WCMD_EXIT:
1624 WCMD_exit (cmdList);
1625 break;
1626 case WCMD_FOR:
1627 case WCMD_IF:
1628 /* Very oddly, probably because of all the special parsing required for
1629 these two commands, neither 'for' nor 'if' is supported when called,
1630 i.e. 'call if 1==1...' will fail. */
1631 if (!retrycall) {
1632 if (i==WCMD_FOR) WCMD_for (p, cmdList);
1633 else if (i==WCMD_IF) WCMD_if (p, cmdList);
1634 break;
1636 /* else: drop through */
1637 default:
1638 prev_echo_mode = echo_mode;
1639 WCMD_run_program (whichcmd, FALSE);
1640 echo_mode = prev_echo_mode;
1642 heap_free(cmd);
1643 heap_free(new_redir);
1645 /* Restore old handles */
1646 for (i=0; i<3; i++) {
1647 if (old_stdhandles[i] != GetStdHandle(idx_stdhandles[i])) {
1648 CloseHandle (GetStdHandle (idx_stdhandles[i]));
1649 SetStdHandle (idx_stdhandles[i], old_stdhandles[i]);
1654 /*************************************************************************
1655 * WCMD_LoadMessage
1656 * Load a string from the resource file, handling any error
1657 * Returns string retrieved from resource file
1659 WCHAR *WCMD_LoadMessage(UINT id) {
1660 static WCHAR msg[2048];
1661 static const WCHAR failedMsg[] = {'F','a','i','l','e','d','!','\0'};
1663 if (!LoadStringW(GetModuleHandleW(NULL), id, msg, ARRAY_SIZE(msg))) {
1664 WINE_FIXME("LoadString failed with %d\n", GetLastError());
1665 strcpyW(msg, failedMsg);
1667 return msg;
1670 /***************************************************************************
1671 * WCMD_DumpCommands
1673 * Dumps out the parsed command line to ensure syntax is correct
1675 static void WCMD_DumpCommands(CMD_LIST *commands) {
1676 CMD_LIST *thisCmd = commands;
1678 WINE_TRACE("Parsed line:\n");
1679 while (thisCmd != NULL) {
1680 WINE_TRACE("%p %d %2.2d %p %s Redir:%s\n",
1681 thisCmd,
1682 thisCmd->prevDelim,
1683 thisCmd->bracketDepth,
1684 thisCmd->nextcommand,
1685 wine_dbgstr_w(thisCmd->command),
1686 wine_dbgstr_w(thisCmd->redirects));
1687 thisCmd = thisCmd->nextcommand;
1691 /***************************************************************************
1692 * WCMD_addCommand
1694 * Adds a command to the current command list
1696 static void WCMD_addCommand(WCHAR *command, int *commandLen,
1697 WCHAR *redirs, int *redirLen,
1698 WCHAR **copyTo, int **copyToLen,
1699 CMD_DELIMITERS prevDelim, int curDepth,
1700 CMD_LIST **lastEntry, CMD_LIST **output) {
1702 CMD_LIST *thisEntry = NULL;
1704 /* Allocate storage for command */
1705 thisEntry = heap_alloc(sizeof(CMD_LIST));
1707 /* Copy in the command */
1708 if (command) {
1709 thisEntry->command = heap_alloc((*commandLen+1) * sizeof(WCHAR));
1710 memcpy(thisEntry->command, command, *commandLen * sizeof(WCHAR));
1711 thisEntry->command[*commandLen] = 0x00;
1713 /* Copy in the redirects */
1714 thisEntry->redirects = heap_alloc((*redirLen+1) * sizeof(WCHAR));
1715 memcpy(thisEntry->redirects, redirs, *redirLen * sizeof(WCHAR));
1716 thisEntry->redirects[*redirLen] = 0x00;
1717 thisEntry->pipeFile[0] = 0x00;
1719 /* Reset the lengths */
1720 *commandLen = 0;
1721 *redirLen = 0;
1722 *copyToLen = commandLen;
1723 *copyTo = command;
1725 } else {
1726 thisEntry->command = NULL;
1727 thisEntry->redirects = NULL;
1728 thisEntry->pipeFile[0] = 0x00;
1731 /* Fill in other fields */
1732 thisEntry->nextcommand = NULL;
1733 thisEntry->prevDelim = prevDelim;
1734 thisEntry->bracketDepth = curDepth;
1735 if (*lastEntry) {
1736 (*lastEntry)->nextcommand = thisEntry;
1737 } else {
1738 *output = thisEntry;
1740 *lastEntry = thisEntry;
1744 /***************************************************************************
1745 * WCMD_IsEndQuote
1747 * Checks if the quote pointed to is the end-quote.
1749 * Quotes end if:
1751 * 1) The current parameter ends at EOL or at the beginning
1752 * of a redirection or pipe and not in a quote section.
1754 * 2) If the next character is a space and not in a quote section.
1756 * Returns TRUE if this is an end quote, and FALSE if it is not.
1759 static BOOL WCMD_IsEndQuote(const WCHAR *quote, int quoteIndex)
1761 int quoteCount = quoteIndex;
1762 int i;
1764 /* If we are not in a quoted section, then we are not an end-quote */
1765 if(quoteIndex == 0)
1767 return FALSE;
1770 /* Check how many quotes are left for this parameter */
1771 for(i=0;quote[i];i++)
1773 if(quote[i] == '"')
1775 quoteCount++;
1778 /* Quote counting ends at EOL, redirection, space or pipe if current quote is complete */
1779 else if(((quoteCount % 2) == 0)
1780 && ((quote[i] == '<') || (quote[i] == '>') || (quote[i] == '|') || (quote[i] == ' ')))
1782 break;
1786 /* If the quote is part of the last part of a series of quotes-on-quotes, then it must
1787 be an end-quote */
1788 if(quoteIndex >= (quoteCount / 2))
1790 return TRUE;
1793 /* No cigar */
1794 return FALSE;
1797 /***************************************************************************
1798 * WCMD_ReadAndParseLine
1800 * Either uses supplied input or
1801 * Reads a file from the handle, and then...
1802 * Parse the text buffer, splitting into separate commands
1803 * - unquoted && strings split 2 commands but the 2nd is flagged as
1804 * following an &&
1805 * - ( as the first character just ups the bracket depth
1806 * - unquoted ) when bracket depth > 0 terminates a bracket and
1807 * adds a CMD_LIST structure with null command
1808 * - Anything else gets put into the command string (including
1809 * redirects)
1811 WCHAR *WCMD_ReadAndParseLine(const WCHAR *optionalcmd, CMD_LIST **output, HANDLE readFrom)
1813 WCHAR *curPos;
1814 int inQuotes = 0;
1815 WCHAR curString[MAXSTRING];
1816 int curStringLen = 0;
1817 WCHAR curRedirs[MAXSTRING];
1818 int curRedirsLen = 0;
1819 WCHAR *curCopyTo;
1820 int *curLen;
1821 int curDepth = 0;
1822 CMD_LIST *lastEntry = NULL;
1823 CMD_DELIMITERS prevDelim = CMD_NONE;
1824 static WCHAR *extraSpace = NULL; /* Deliberately never freed */
1825 static const WCHAR remCmd[] = {'r','e','m'};
1826 static const WCHAR forCmd[] = {'f','o','r'};
1827 static const WCHAR ifCmd[] = {'i','f'};
1828 static const WCHAR ifElse[] = {'e','l','s','e'};
1829 BOOL inOneLine = FALSE;
1830 BOOL inFor = FALSE;
1831 BOOL inIn = FALSE;
1832 BOOL inIf = FALSE;
1833 BOOL inElse= FALSE;
1834 BOOL onlyWhiteSpace = FALSE;
1835 BOOL lastWasWhiteSpace = FALSE;
1836 BOOL lastWasDo = FALSE;
1837 BOOL lastWasIn = FALSE;
1838 BOOL lastWasElse = FALSE;
1839 BOOL lastWasRedirect = TRUE;
1840 BOOL lastWasCaret = FALSE;
1842 /* Allocate working space for a command read from keyboard, file etc */
1843 if (!extraSpace)
1844 extraSpace = heap_alloc((MAXSTRING+1) * sizeof(WCHAR));
1845 if (!extraSpace)
1847 WINE_ERR("Could not allocate memory for extraSpace\n");
1848 return NULL;
1851 /* If initial command read in, use that, otherwise get input from handle */
1852 if (optionalcmd != NULL) {
1853 strcpyW(extraSpace, optionalcmd);
1854 } else if (readFrom == INVALID_HANDLE_VALUE) {
1855 WINE_FIXME("No command nor handle supplied\n");
1856 } else {
1857 if (!WCMD_fgets(extraSpace, MAXSTRING, readFrom))
1858 return NULL;
1860 curPos = extraSpace;
1862 /* Handle truncated input - issue warning */
1863 if (strlenW(extraSpace) == MAXSTRING -1) {
1864 WCMD_output_asis_stderr(WCMD_LoadMessage(WCMD_TRUNCATEDLINE));
1865 WCMD_output_asis_stderr(extraSpace);
1866 WCMD_output_asis_stderr(newlineW);
1869 /* Replace env vars if in a batch context */
1870 if (context) handleExpansion(extraSpace, FALSE, FALSE);
1872 /* Skip preceding whitespace */
1873 while (*curPos == ' ' || *curPos == '\t') curPos++;
1875 /* Show prompt before batch line IF echo is on and in batch program */
1876 if (context && echo_mode && *curPos && (*curPos != '@')) {
1877 static const WCHAR echoDot[] = {'e','c','h','o','.'};
1878 static const WCHAR echoCol[] = {'e','c','h','o',':'};
1879 static const WCHAR echoSlash[] = {'e','c','h','o','/'};
1880 const DWORD len = ARRAY_SIZE(echoDot);
1881 DWORD curr_size = strlenW(curPos);
1882 DWORD min_len = (curr_size < len ? curr_size : len);
1883 WCMD_show_prompt();
1884 WCMD_output_asis(curPos);
1885 /* I don't know why Windows puts a space here but it does */
1886 /* Except for lines starting with 'echo.', 'echo:' or 'echo/'. Ask MS why */
1887 if (CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
1888 curPos, min_len, echoDot, len) != CSTR_EQUAL
1889 && CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
1890 curPos, min_len, echoCol, len) != CSTR_EQUAL
1891 && CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
1892 curPos, min_len, echoSlash, len) != CSTR_EQUAL)
1894 WCMD_output_asis(spaceW);
1896 WCMD_output_asis(newlineW);
1899 /* Skip repeated 'no echo' characters */
1900 while (*curPos == '@') curPos++;
1902 /* Start with an empty string, copying to the command string */
1903 curStringLen = 0;
1904 curRedirsLen = 0;
1905 curCopyTo = curString;
1906 curLen = &curStringLen;
1907 lastWasRedirect = FALSE; /* Required e.g. for spaces between > and filename */
1909 /* Parse every character on the line being processed */
1910 while (*curPos != 0x00) {
1912 WCHAR thisChar;
1914 /* Debugging AID:
1915 WINE_TRACE("Looking at '%c' (len:%d, lws:%d, ows:%d)\n", *curPos, *curLen,
1916 lastWasWhiteSpace, onlyWhiteSpace);
1919 /* Prevent overflow caused by the caret escape char */
1920 if (*curLen >= MAXSTRING) {
1921 WINE_ERR("Overflow detected in command\n");
1922 return NULL;
1925 /* Certain commands need special handling */
1926 if (curStringLen == 0 && curCopyTo == curString) {
1927 static const WCHAR forDO[] = {'d','o'};
1929 /* If command starts with 'rem ' or identifies a label, ignore any &&, ( etc. */
1930 if (WCMD_keyword_ws_found(remCmd, ARRAY_SIZE(remCmd), curPos) || *curPos == ':') {
1931 inOneLine = TRUE;
1933 } else if (WCMD_keyword_ws_found(forCmd, ARRAY_SIZE(forCmd), curPos)) {
1934 inFor = TRUE;
1936 /* If command starts with 'if ' or 'else ', handle ('s mid line. We should ensure this
1937 is only true in the command portion of the IF statement, but this
1938 should suffice for now
1939 FIXME: Silly syntax like "if 1(==1( (
1940 echo they equal
1941 )" will be parsed wrong */
1942 } else if (WCMD_keyword_ws_found(ifCmd, ARRAY_SIZE(ifCmd), curPos)) {
1943 inIf = TRUE;
1945 } else if (WCMD_keyword_ws_found(ifElse, ARRAY_SIZE(ifElse), curPos)) {
1946 const int keyw_len = ARRAY_SIZE(ifElse) + 1;
1947 inElse = TRUE;
1948 lastWasElse = TRUE;
1949 onlyWhiteSpace = TRUE;
1950 memcpy(&curCopyTo[*curLen], curPos, keyw_len*sizeof(WCHAR));
1951 (*curLen)+=keyw_len;
1952 curPos+=keyw_len;
1953 continue;
1955 /* In a for loop, the DO command will follow a close bracket followed by
1956 whitespace, followed by DO, ie closeBracket inserts a NULL entry, curLen
1957 is then 0, and all whitespace is skipped */
1958 } else if (inFor && WCMD_keyword_ws_found(forDO, ARRAY_SIZE(forDO), curPos)) {
1959 const int keyw_len = ARRAY_SIZE(forDO) + 1;
1960 WINE_TRACE("Found 'DO '\n");
1961 lastWasDo = TRUE;
1962 onlyWhiteSpace = TRUE;
1963 memcpy(&curCopyTo[*curLen], curPos, keyw_len*sizeof(WCHAR));
1964 (*curLen)+=keyw_len;
1965 curPos+=keyw_len;
1966 continue;
1968 } else if (curCopyTo == curString) {
1970 /* Special handling for the 'FOR' command */
1971 if (inFor && lastWasWhiteSpace) {
1972 static const WCHAR forIN[] = {'i','n'};
1974 WINE_TRACE("Found 'FOR ', comparing next parm: '%s'\n", wine_dbgstr_w(curPos));
1976 if (WCMD_keyword_ws_found(forIN, ARRAY_SIZE(forIN), curPos)) {
1977 const int keyw_len = ARRAY_SIZE(forIN) + 1;
1978 WINE_TRACE("Found 'IN '\n");
1979 lastWasIn = TRUE;
1980 onlyWhiteSpace = TRUE;
1981 memcpy(&curCopyTo[*curLen], curPos, keyw_len*sizeof(WCHAR));
1982 (*curLen)+=keyw_len;
1983 curPos+=keyw_len;
1984 continue;
1989 /* Nothing 'ends' a one line statement (e.g. REM or :labels mean
1990 the &&, quotes and redirection etc are ineffective, so just force
1991 the use of the default processing by skipping character specific
1992 matching below) */
1993 if (!inOneLine) thisChar = *curPos;
1994 else thisChar = 'X'; /* Character with no special processing */
1996 lastWasWhiteSpace = FALSE; /* Will be reset below */
1997 lastWasCaret = FALSE;
1999 switch (thisChar) {
2001 case '=': /* drop through - ignore token delimiters at the start of a command */
2002 case ',': /* drop through - ignore token delimiters at the start of a command */
2003 case '\t':/* drop through - ignore token delimiters at the start of a command */
2004 case ' ':
2005 /* If a redirect in place, it ends here */
2006 if (!inQuotes && !lastWasRedirect) {
2008 /* If finishing off a redirect, add a whitespace delimiter */
2009 if (curCopyTo == curRedirs) {
2010 curCopyTo[(*curLen)++] = ' ';
2012 curCopyTo = curString;
2013 curLen = &curStringLen;
2015 if (*curLen > 0) {
2016 curCopyTo[(*curLen)++] = *curPos;
2019 /* Remember just processed whitespace */
2020 lastWasWhiteSpace = TRUE;
2022 break;
2024 case '>': /* drop through - handle redirect chars the same */
2025 case '<':
2026 /* Make a redirect start here */
2027 if (!inQuotes) {
2028 curCopyTo = curRedirs;
2029 curLen = &curRedirsLen;
2030 lastWasRedirect = TRUE;
2033 /* See if 1>, 2> etc, in which case we have some patching up
2034 to do (provided there's a preceding whitespace, and enough
2035 chars read so far) */
2036 if (curStringLen > 2
2037 && (*(curPos-1)>='1') && (*(curPos-1)<='9')
2038 && ((*(curPos-2)==' ') || (*(curPos-2)=='\t'))) {
2039 curStringLen--;
2040 curString[curStringLen] = 0x00;
2041 curCopyTo[(*curLen)++] = *(curPos-1);
2044 curCopyTo[(*curLen)++] = *curPos;
2046 /* If a redirect is immediately followed by '&' (ie. 2>&1) then
2047 do not process that ampersand as an AND operator */
2048 if (thisChar == '>' && *(curPos+1) == '&') {
2049 curCopyTo[(*curLen)++] = *(curPos+1);
2050 curPos++;
2052 break;
2054 case '|': /* Pipe character only if not || */
2055 if (!inQuotes) {
2056 lastWasRedirect = FALSE;
2058 /* Add an entry to the command list */
2059 if (curStringLen > 0) {
2061 /* Add the current command */
2062 WCMD_addCommand(curString, &curStringLen,
2063 curRedirs, &curRedirsLen,
2064 &curCopyTo, &curLen,
2065 prevDelim, curDepth,
2066 &lastEntry, output);
2070 if (*(curPos+1) == '|') {
2071 curPos++; /* Skip other | */
2072 prevDelim = CMD_ONFAILURE;
2073 } else {
2074 prevDelim = CMD_PIPE;
2076 } else {
2077 curCopyTo[(*curLen)++] = *curPos;
2079 break;
2081 case '"': if (WCMD_IsEndQuote(curPos, inQuotes)) {
2082 inQuotes--;
2083 } else {
2084 inQuotes++; /* Quotes within quotes are fun! */
2086 curCopyTo[(*curLen)++] = *curPos;
2087 lastWasRedirect = FALSE;
2088 break;
2090 case '(': /* If a '(' is the first non whitespace in a command portion
2091 ie start of line or just after &&, then we read until an
2092 unquoted ) is found */
2093 WINE_TRACE("Found '(' conditions: curLen(%d), inQ(%d), onlyWS(%d)"
2094 ", for(%d, In:%d, Do:%d)"
2095 ", if(%d, else:%d, lwe:%d)\n",
2096 *curLen, inQuotes,
2097 onlyWhiteSpace,
2098 inFor, lastWasIn, lastWasDo,
2099 inIf, inElse, lastWasElse);
2100 lastWasRedirect = FALSE;
2102 /* Ignore open brackets inside the for set */
2103 if (*curLen == 0 && !inIn) {
2104 curDepth++;
2106 /* If in quotes, ignore brackets */
2107 } else if (inQuotes) {
2108 curCopyTo[(*curLen)++] = *curPos;
2110 /* In a FOR loop, an unquoted '(' may occur straight after
2111 IN or DO
2112 In an IF statement just handle it regardless as we don't
2113 parse the operands
2114 In an ELSE statement, only allow it straight away after
2115 the ELSE and whitespace
2117 } else if (inIf ||
2118 (inElse && lastWasElse && onlyWhiteSpace) ||
2119 (inFor && (lastWasIn || lastWasDo) && onlyWhiteSpace)) {
2121 /* If entering into an 'IN', set inIn */
2122 if (inFor && lastWasIn && onlyWhiteSpace) {
2123 WINE_TRACE("Inside an IN\n");
2124 inIn = TRUE;
2127 /* Add the current command */
2128 WCMD_addCommand(curString, &curStringLen,
2129 curRedirs, &curRedirsLen,
2130 &curCopyTo, &curLen,
2131 prevDelim, curDepth,
2132 &lastEntry, output);
2134 curDepth++;
2135 } else {
2136 curCopyTo[(*curLen)++] = *curPos;
2138 break;
2140 case '^': if (!inQuotes) {
2141 /* If we reach the end of the input, we need to wait for more */
2142 if (*(curPos+1) == 0x00) {
2143 lastWasCaret = TRUE;
2144 WINE_TRACE("Caret found at end of line\n");
2145 break;
2147 curPos++;
2149 curCopyTo[(*curLen)++] = *curPos;
2150 break;
2152 case '&': if (!inQuotes) {
2153 lastWasRedirect = FALSE;
2155 /* Add an entry to the command list */
2156 if (curStringLen > 0) {
2158 /* Add the current command */
2159 WCMD_addCommand(curString, &curStringLen,
2160 curRedirs, &curRedirsLen,
2161 &curCopyTo, &curLen,
2162 prevDelim, curDepth,
2163 &lastEntry, output);
2167 if (*(curPos+1) == '&') {
2168 curPos++; /* Skip other & */
2169 prevDelim = CMD_ONSUCCESS;
2170 } else {
2171 prevDelim = CMD_NONE;
2173 } else {
2174 curCopyTo[(*curLen)++] = *curPos;
2176 break;
2178 case ')': if (!inQuotes && curDepth > 0) {
2179 lastWasRedirect = FALSE;
2181 /* Add the current command if there is one */
2182 if (curStringLen) {
2184 /* Add the current command */
2185 WCMD_addCommand(curString, &curStringLen,
2186 curRedirs, &curRedirsLen,
2187 &curCopyTo, &curLen,
2188 prevDelim, curDepth,
2189 &lastEntry, output);
2192 /* Add an empty entry to the command list */
2193 prevDelim = CMD_NONE;
2194 WCMD_addCommand(NULL, &curStringLen,
2195 curRedirs, &curRedirsLen,
2196 &curCopyTo, &curLen,
2197 prevDelim, curDepth,
2198 &lastEntry, output);
2199 curDepth--;
2201 /* Leave inIn if necessary */
2202 if (inIn) inIn = FALSE;
2203 } else {
2204 curCopyTo[(*curLen)++] = *curPos;
2206 break;
2207 default:
2208 lastWasRedirect = FALSE;
2209 curCopyTo[(*curLen)++] = *curPos;
2212 curPos++;
2214 /* At various times we need to know if we have only skipped whitespace,
2215 so reset this variable and then it will remain true until a non
2216 whitespace is found */
2217 if ((thisChar != ' ') && (thisChar != '\t') && (thisChar != '\n'))
2218 onlyWhiteSpace = FALSE;
2220 /* Flag end of interest in FOR DO and IN parms once something has been processed */
2221 if (!lastWasWhiteSpace) {
2222 lastWasIn = lastWasDo = FALSE;
2225 /* If we have reached the end, add this command into the list
2226 Do not add command to list if escape char ^ was last */
2227 if (*curPos == 0x00 && !lastWasCaret && *curLen > 0) {
2229 /* Add an entry to the command list */
2230 WCMD_addCommand(curString, &curStringLen,
2231 curRedirs, &curRedirsLen,
2232 &curCopyTo, &curLen,
2233 prevDelim, curDepth,
2234 &lastEntry, output);
2237 /* If we have reached the end of the string, see if bracketing or
2238 final caret is outstanding */
2239 if (*curPos == 0x00 && (curDepth > 0 || lastWasCaret) &&
2240 readFrom != INVALID_HANDLE_VALUE) {
2241 WCHAR *extraData;
2243 WINE_TRACE("Need to read more data as outstanding brackets or carets\n");
2244 inOneLine = FALSE;
2245 prevDelim = CMD_NONE;
2246 inQuotes = 0;
2247 memset(extraSpace, 0x00, (MAXSTRING+1) * sizeof(WCHAR));
2248 extraData = extraSpace;
2250 /* Read more, skipping any blank lines */
2251 do {
2252 WINE_TRACE("Read more input\n");
2253 if (!context) WCMD_output_asis( WCMD_LoadMessage(WCMD_MOREPROMPT));
2254 if (!WCMD_fgets(extraData, MAXSTRING, readFrom))
2255 break;
2257 /* Edge case for carets - a completely blank line (i.e. was just
2258 CRLF) is oddly added as an LF but then more data is received (but
2259 only once more!) */
2260 if (lastWasCaret) {
2261 if (*extraSpace == 0x00) {
2262 WINE_TRACE("Read nothing, so appending LF char and will try again\n");
2263 *extraData++ = '\r';
2264 *extraData = 0x00;
2265 } else break;
2268 } while (*extraData == 0x00);
2269 curPos = extraSpace;
2270 if (context) handleExpansion(extraSpace, FALSE, FALSE);
2271 /* Continue to echo commands IF echo is on and in batch program */
2272 if (context && echo_mode && extraSpace[0] && (extraSpace[0] != '@')) {
2273 WCMD_output_asis(extraSpace);
2274 WCMD_output_asis(newlineW);
2279 /* Dump out the parsed output */
2280 WCMD_DumpCommands(*output);
2282 return extraSpace;
2285 /***************************************************************************
2286 * WCMD_process_commands
2288 * Process all the commands read in so far
2290 CMD_LIST *WCMD_process_commands(CMD_LIST *thisCmd, BOOL oneBracket,
2291 BOOL retrycall) {
2293 int bdepth = -1;
2295 if (thisCmd && oneBracket) bdepth = thisCmd->bracketDepth;
2297 /* Loop through the commands, processing them one by one */
2298 while (thisCmd) {
2300 CMD_LIST *origCmd = thisCmd;
2302 /* If processing one bracket only, and we find the end bracket
2303 entry (or less), return */
2304 if (oneBracket && !thisCmd->command &&
2305 bdepth <= thisCmd->bracketDepth) {
2306 WINE_TRACE("Finished bracket @ %p, next command is %p\n",
2307 thisCmd, thisCmd->nextcommand);
2308 return thisCmd->nextcommand;
2311 /* Ignore the NULL entries a ')' inserts (Only 'if' cares
2312 about them and it will be handled in there)
2313 Also, skip over any batch labels (eg. :fred) */
2314 if (thisCmd->command && thisCmd->command[0] != ':') {
2315 WINE_TRACE("Executing command: '%s'\n", wine_dbgstr_w(thisCmd->command));
2316 WCMD_execute (thisCmd->command, thisCmd->redirects, &thisCmd, retrycall);
2319 /* Step on unless the command itself already stepped on */
2320 if (thisCmd == origCmd) thisCmd = thisCmd->nextcommand;
2322 return NULL;
2325 /***************************************************************************
2326 * WCMD_free_commands
2328 * Frees the storage held for a parsed command line
2329 * - This is not done in the process_commands, as eventually the current
2330 * pointer will be modified within the commands, and hence a single free
2331 * routine is simpler
2333 void WCMD_free_commands(CMD_LIST *cmds) {
2335 /* Loop through the commands, freeing them one by one */
2336 while (cmds) {
2337 CMD_LIST *thisCmd = cmds;
2338 cmds = cmds->nextcommand;
2339 heap_free(thisCmd->command);
2340 heap_free(thisCmd->redirects);
2341 heap_free(thisCmd);
2346 /*****************************************************************************
2347 * Main entry point. This is a console application so we have a main() not a
2348 * winmain().
2351 int wmain (int argc, WCHAR *argvW[])
2353 int args;
2354 WCHAR *cmdLine = NULL;
2355 WCHAR *cmd = NULL;
2356 WCHAR *argPos = NULL;
2357 WCHAR string[1024];
2358 WCHAR envvar[4];
2359 BOOL opt_q;
2360 int opt_t = 0;
2361 static const WCHAR offW[] = {'O','F','F','\0'};
2362 static const WCHAR promptW[] = {'P','R','O','M','P','T','\0'};
2363 static const WCHAR defaultpromptW[] = {'$','P','$','G','\0'};
2364 CMD_LIST *toExecute = NULL; /* Commands left to be executed */
2365 OSVERSIONINFOW osv;
2366 char osver[50];
2368 srand(time(NULL));
2370 /* Get the windows version being emulated */
2371 osv.dwOSVersionInfoSize = sizeof(osv);
2372 GetVersionExW(&osv);
2374 /* Pre initialize some messages */
2375 strcpyW(anykey, WCMD_LoadMessage(WCMD_ANYKEY));
2376 sprintf(osver, "%d.%d.%d (%s)", osv.dwMajorVersion, osv.dwMinorVersion,
2377 osv.dwBuildNumber, PACKAGE_VERSION);
2378 cmd = WCMD_format_string(WCMD_LoadMessage(WCMD_VERSION), osver);
2379 strcpyW(version_string, cmd);
2380 LocalFree(cmd);
2381 cmd = NULL;
2383 /* Can't use argc/argv as it will have stripped quotes from parameters
2384 * meaning cmd.exe /C echo "quoted string" is impossible
2386 cmdLine = GetCommandLineW();
2387 WINE_TRACE("Full commandline '%s'\n", wine_dbgstr_w(cmdLine));
2388 args = 0;
2390 opt_c = opt_k = opt_q = opt_s = FALSE;
2391 WCMD_parameter(cmdLine, args, &argPos, TRUE, TRUE);
2392 while (argPos && argPos[0] != 0x00)
2394 WCHAR c;
2395 WINE_TRACE("Command line parm: '%s'\n", wine_dbgstr_w(argPos));
2396 if (argPos[0]!='/' || argPos[1]=='\0') {
2397 args++;
2398 WCMD_parameter(cmdLine, args, &argPos, TRUE, TRUE);
2399 continue;
2402 c=argPos[1];
2403 if (tolowerW(c)=='c') {
2404 opt_c = TRUE;
2405 } else if (tolowerW(c)=='q') {
2406 opt_q = TRUE;
2407 } else if (tolowerW(c)=='k') {
2408 opt_k = TRUE;
2409 } else if (tolowerW(c)=='s') {
2410 opt_s = TRUE;
2411 } else if (tolowerW(c)=='a') {
2412 unicodeOutput = FALSE;
2413 } else if (tolowerW(c)=='u') {
2414 unicodeOutput = TRUE;
2415 } else if (tolowerW(c)=='v' && argPos[2]==':') {
2416 delayedsubst = strncmpiW(&argPos[3], offW, 3);
2417 if (delayedsubst) WINE_TRACE("Delayed substitution is on\n");
2418 } else if (tolowerW(c)=='t' && argPos[2]==':') {
2419 opt_t=strtoulW(&argPos[3], NULL, 16);
2420 } else if (tolowerW(c)=='x' || tolowerW(c)=='y') {
2421 /* Ignored for compatibility with Windows */
2424 if (argPos[2]==0 || argPos[2]==' ' || argPos[2]=='\t' ||
2425 tolowerW(c)=='v') {
2426 args++;
2427 WCMD_parameter(cmdLine, args, &argPos, TRUE, TRUE);
2429 else /* handle `cmd /cnotepad.exe` and `cmd /x/c ...` */
2431 /* Do not step to next parameter, instead carry on parsing this one */
2432 argPos+=2;
2435 if (opt_c || opt_k) /* break out of parsing immediately after c or k */
2436 break;
2439 if (opt_q) {
2440 WCMD_echo(offW);
2443 /* Until we start to read from the keyboard, stay as non-interactive */
2444 interactive = FALSE;
2446 SetEnvironmentVariableW(promptW, defaultpromptW);
2448 if (opt_c || opt_k) {
2449 int len;
2450 WCHAR *q1 = NULL,*q2 = NULL,*p;
2452 /* Handle very edge case error scenario, "cmd.exe /c" ie when there are no
2453 * parameters after the /C or /K by pretending there was a single space */
2454 if (argPos == NULL) argPos = (WCHAR *)spaceW;
2456 /* Take a copy */
2457 cmd = heap_strdupW(argPos);
2459 /* opt_s left unflagged if the command starts with and contains exactly
2460 * one quoted string (exactly two quote characters). The quoted string
2461 * must be an executable name that has whitespace and must not have the
2462 * following characters: &<>()@^| */
2464 if (!opt_s) {
2465 /* 1. Confirm there is at least one quote */
2466 q1 = strchrW(argPos, '"');
2467 if (!q1) opt_s=1;
2470 if (!opt_s) {
2471 /* 2. Confirm there is a second quote */
2472 q2 = strchrW(q1+1, '"');
2473 if (!q2) opt_s=1;
2476 if (!opt_s) {
2477 /* 3. Ensure there are no more quotes */
2478 if (strchrW(q2+1, '"')) opt_s=1;
2481 /* check first parameter for a space and invalid characters. There must not be any
2482 * invalid characters, but there must be one or more whitespace */
2483 if (!opt_s) {
2484 opt_s = TRUE;
2485 p=q1;
2486 while (p!=q2) {
2487 if (*p=='&' || *p=='<' || *p=='>' || *p=='(' || *p==')'
2488 || *p=='@' || *p=='^' || *p=='|') {
2489 opt_s = TRUE;
2490 break;
2492 if (*p==' ' || *p=='\t')
2493 opt_s = FALSE;
2494 p++;
2498 WINE_TRACE("/c command line: '%s'\n", wine_dbgstr_w(cmd));
2500 /* Finally, we only stay in new mode IF the first parameter is quoted and
2501 is a valid executable, i.e. must exist, otherwise drop back to old mode */
2502 if (!opt_s) {
2503 WCHAR *thisArg = WCMD_parameter(cmd, 0, NULL, FALSE, TRUE);
2504 WCHAR pathext[MAXSTRING];
2505 BOOL found = FALSE;
2507 /* Now extract PATHEXT */
2508 len = GetEnvironmentVariableW(envPathExt, pathext, ARRAY_SIZE(pathext));
2509 if ((len == 0) || (len >= ARRAY_SIZE(pathext))) {
2510 strcpyW (pathext, dfltPathExt);
2513 /* If the supplied parameter has any directory information, look there */
2514 WINE_TRACE("First parameter is '%s'\n", wine_dbgstr_w(thisArg));
2515 if (strchrW(thisArg, '\\') != NULL) {
2517 GetFullPathNameW(thisArg, ARRAY_SIZE(string), string, NULL);
2518 WINE_TRACE("Full path name '%s'\n", wine_dbgstr_w(string));
2519 p = string + strlenW(string);
2521 /* Does file exist with this name? */
2522 if (GetFileAttributesW(string) != INVALID_FILE_ATTRIBUTES) {
2523 WINE_TRACE("Found file as '%s'\n", wine_dbgstr_w(string));
2524 found = TRUE;
2525 } else {
2526 WCHAR *thisExt = pathext;
2528 /* No - try with each of the PATHEXT extensions */
2529 while (!found && thisExt) {
2530 WCHAR *nextExt = strchrW(thisExt, ';');
2532 if (nextExt) {
2533 memcpy(p, thisExt, (nextExt-thisExt) * sizeof(WCHAR));
2534 p[(nextExt-thisExt)] = 0x00;
2535 thisExt = nextExt+1;
2536 } else {
2537 strcpyW(p, thisExt);
2538 thisExt = NULL;
2541 /* Does file exist with this extension appended? */
2542 if (GetFileAttributesW(string) != INVALID_FILE_ATTRIBUTES) {
2543 WINE_TRACE("Found file as '%s'\n", wine_dbgstr_w(string));
2544 found = TRUE;
2549 /* Otherwise we now need to look in the path to see if we can find it */
2550 } else {
2551 /* Does file exist with this name? */
2552 if (SearchPathW(NULL, thisArg, NULL, ARRAY_SIZE(string), string, NULL) != 0) {
2553 WINE_TRACE("Found on path as '%s'\n", wine_dbgstr_w(string));
2554 found = TRUE;
2555 } else {
2556 WCHAR *thisExt = pathext;
2558 /* No - try with each of the PATHEXT extensions */
2559 while (!found && thisExt) {
2560 WCHAR *nextExt = strchrW(thisExt, ';');
2562 if (nextExt) {
2563 *nextExt = 0;
2564 nextExt = nextExt+1;
2565 } else {
2566 nextExt = NULL;
2569 /* Does file exist with this extension? */
2570 if (SearchPathW(NULL, thisArg, thisExt, ARRAY_SIZE(string), string, NULL) != 0) {
2571 WINE_TRACE("Found on path as '%s' with extension '%s'\n", wine_dbgstr_w(string),
2572 wine_dbgstr_w(thisExt));
2573 found = TRUE;
2575 thisExt = nextExt;
2580 /* If not found, drop back to old behaviour */
2581 if (!found) {
2582 WINE_TRACE("Binary not found, dropping back to old behaviour\n");
2583 opt_s = TRUE;
2588 /* strip first and last quote characters if opt_s; check for invalid
2589 * executable is done later */
2590 if (opt_s && *cmd=='\"')
2591 WCMD_strip_quotes(cmd);
2594 /* Save cwd into appropriate env var (Must be before the /c processing */
2595 GetCurrentDirectoryW(ARRAY_SIZE(string), string);
2596 if (IsCharAlphaW(string[0]) && string[1] == ':') {
2597 static const WCHAR fmt[] = {'=','%','c',':','\0'};
2598 wsprintfW(envvar, fmt, string[0]);
2599 SetEnvironmentVariableW(envvar, string);
2600 WINE_TRACE("Set %s to %s\n", wine_dbgstr_w(envvar), wine_dbgstr_w(string));
2603 if (opt_c) {
2604 /* If we do a "cmd /c command", we don't want to allocate a new
2605 * console since the command returns immediately. Rather, we use
2606 * the currently allocated input and output handles. This allows
2607 * us to pipe to and read from the command interpreter.
2610 /* Parse the command string, without reading any more input */
2611 WCMD_ReadAndParseLine(cmd, &toExecute, INVALID_HANDLE_VALUE);
2612 WCMD_process_commands(toExecute, FALSE, FALSE);
2613 WCMD_free_commands(toExecute);
2614 toExecute = NULL;
2616 heap_free(cmd);
2617 return errorlevel;
2620 SetConsoleTitleW(WCMD_LoadMessage(WCMD_CONSTITLE));
2622 /* Note: cmd.exe /c dir does not get a new color, /k dir does */
2623 if (opt_t) {
2624 if (!(((opt_t & 0xF0) >> 4) == (opt_t & 0x0F))) {
2625 defaultColor = opt_t & 0xFF;
2626 param1[0] = 0x00;
2627 WCMD_color();
2629 } else {
2630 /* Check HKCU\Software\Microsoft\Command Processor
2631 Then HKLM\Software\Microsoft\Command Processor
2632 for defaultcolour value
2633 Note Can be supplied as DWORD or REG_SZ
2634 Note2 When supplied as REG_SZ it's in decimal!!! */
2635 HKEY key;
2636 DWORD type;
2637 DWORD value=0, size=4;
2638 static const WCHAR regKeyW[] = {'S','o','f','t','w','a','r','e','\\',
2639 'M','i','c','r','o','s','o','f','t','\\',
2640 'C','o','m','m','a','n','d',' ','P','r','o','c','e','s','s','o','r','\0'};
2641 static const WCHAR dfltColorW[] = {'D','e','f','a','u','l','t','C','o','l','o','r','\0'};
2643 if (RegOpenKeyExW(HKEY_CURRENT_USER, regKeyW,
2644 0, KEY_READ, &key) == ERROR_SUCCESS) {
2645 WCHAR strvalue[4];
2647 /* See if DWORD or REG_SZ */
2648 if (RegQueryValueExW(key, dfltColorW, NULL, &type,
2649 NULL, NULL) == ERROR_SUCCESS) {
2650 if (type == REG_DWORD) {
2651 size = sizeof(DWORD);
2652 RegQueryValueExW(key, dfltColorW, NULL, NULL,
2653 (LPBYTE)&value, &size);
2654 } else if (type == REG_SZ) {
2655 size = ARRAY_SIZE(strvalue);
2656 RegQueryValueExW(key, dfltColorW, NULL, NULL,
2657 (LPBYTE)strvalue, &size);
2658 value = strtoulW(strvalue, NULL, 10);
2661 RegCloseKey(key);
2664 if (value == 0 && RegOpenKeyExW(HKEY_LOCAL_MACHINE, regKeyW,
2665 0, KEY_READ, &key) == ERROR_SUCCESS) {
2666 WCHAR strvalue[4];
2668 /* See if DWORD or REG_SZ */
2669 if (RegQueryValueExW(key, dfltColorW, NULL, &type,
2670 NULL, NULL) == ERROR_SUCCESS) {
2671 if (type == REG_DWORD) {
2672 size = sizeof(DWORD);
2673 RegQueryValueExW(key, dfltColorW, NULL, NULL,
2674 (LPBYTE)&value, &size);
2675 } else if (type == REG_SZ) {
2676 size = ARRAY_SIZE(strvalue);
2677 RegQueryValueExW(key, dfltColorW, NULL, NULL,
2678 (LPBYTE)strvalue, &size);
2679 value = strtoulW(strvalue, NULL, 10);
2682 RegCloseKey(key);
2685 /* If one found, set the screen to that colour */
2686 if (!(((value & 0xF0) >> 4) == (value & 0x0F))) {
2687 defaultColor = value & 0xFF;
2688 param1[0] = 0x00;
2689 WCMD_color();
2694 if (opt_k) {
2695 /* Parse the command string, without reading any more input */
2696 WCMD_ReadAndParseLine(cmd, &toExecute, INVALID_HANDLE_VALUE);
2697 WCMD_process_commands(toExecute, FALSE, FALSE);
2698 WCMD_free_commands(toExecute);
2699 toExecute = NULL;
2700 heap_free(cmd);
2704 * Loop forever getting commands and executing them.
2707 interactive = TRUE;
2708 if (!opt_k) WCMD_version ();
2709 while (TRUE) {
2711 /* Read until EOF (which for std input is never, but if redirect
2712 in place, may occur */
2713 if (echo_mode) WCMD_show_prompt();
2714 if (!WCMD_ReadAndParseLine(NULL, &toExecute, GetStdHandle(STD_INPUT_HANDLE)))
2715 break;
2716 WCMD_process_commands(toExecute, FALSE, FALSE);
2717 WCMD_free_commands(toExecute);
2718 toExecute = NULL;
2720 return 0;