cmd: set "var=value" ignores trailing characters.
[wine/multimedia.git] / programs / cmd / wcmdmain.c
blob0d4575bd9f1f9f514ffc245b98ee3757b9ab279f
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[MAX_PATH], 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 its 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 CDECL 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 CDECL 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* CDECL 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, sizeof(string)/sizeof(WCHAR), &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,
347 sizeof(prompt_string)/sizeof(WCHAR));
348 if ((len == 0) || (len >= (sizeof(prompt_string)/sizeof(WCHAR)))) {
349 static const WCHAR dfltPrompt[] = {'$','P','$','G','\0'};
350 strcpyW (prompt_string, dfltPrompt);
352 p = prompt_string;
353 q = out_string;
354 *q++ = '\r';
355 *q++ = '\n';
356 *q = '\0';
357 while (*p != '\0') {
358 if (*p != '$') {
359 *q++ = *p++;
360 *q = '\0';
362 else {
363 p++;
364 switch (toupper(*p)) {
365 case '$':
366 *q++ = '$';
367 break;
368 case 'A':
369 *q++ = '&';
370 break;
371 case 'B':
372 *q++ = '|';
373 break;
374 case 'C':
375 *q++ = '(';
376 break;
377 case 'D':
378 GetDateFormatW(LOCALE_USER_DEFAULT, DATE_SHORTDATE, NULL, NULL, q, MAX_PATH);
379 while (*q) q++;
380 break;
381 case 'E':
382 *q++ = '\E';
383 break;
384 case 'F':
385 *q++ = ')';
386 break;
387 case 'G':
388 *q++ = '>';
389 break;
390 case 'H':
391 *q++ = '\b';
392 break;
393 case 'L':
394 *q++ = '<';
395 break;
396 case 'N':
397 status = GetCurrentDirectoryW(sizeof(curdir)/sizeof(WCHAR), curdir);
398 if (status) {
399 *q++ = curdir[0];
401 break;
402 case 'P':
403 status = GetCurrentDirectoryW(sizeof(curdir)/sizeof(WCHAR), curdir);
404 if (status) {
405 strcatW (q, curdir);
406 while (*q) q++;
408 break;
409 case 'Q':
410 *q++ = '=';
411 break;
412 case 'S':
413 *q++ = ' ';
414 break;
415 case 'T':
416 GetTimeFormatW(LOCALE_USER_DEFAULT, 0, NULL, NULL, q, MAX_PATH);
417 while (*q) q++;
418 break;
419 case 'V':
420 strcatW (q, version_string);
421 while (*q) q++;
422 break;
423 case '_':
424 *q++ = '\n';
425 break;
426 case '+':
427 if (pushd_directories) {
428 memset(q, '+', pushd_directories->u.stackdepth);
429 q = q + pushd_directories->u.stackdepth;
431 break;
433 p++;
434 *q = '\0';
437 WCMD_output_asis (out_string);
440 void *heap_alloc(size_t size)
442 void *ret;
444 ret = HeapAlloc(GetProcessHeap(), 0, size);
445 if(!ret) {
446 ERR("Out of memory\n");
447 ExitProcess(1);
450 return ret;
453 /*************************************************************************
454 * WCMD_strsubstW
455 * Replaces a portion of a Unicode string with the specified string.
456 * It's up to the caller to ensure there is enough space in the
457 * destination buffer.
459 void WCMD_strsubstW(WCHAR *start, const WCHAR *next, const WCHAR *insert, int len) {
461 if (len < 0)
462 len=insert ? lstrlenW(insert) : 0;
463 if (start+len != next)
464 memmove(start+len, next, (strlenW(next) + 1) * sizeof(*next));
465 if (insert)
466 memcpy(start, insert, len * sizeof(*insert));
469 /***************************************************************************
470 * WCMD_skip_leading_spaces
472 * Return a pointer to the first non-whitespace character of string.
473 * Does not modify the input string.
475 WCHAR *WCMD_skip_leading_spaces (WCHAR *string) {
477 WCHAR *ptr;
479 ptr = string;
480 while (*ptr == ' ' || *ptr == '\t') ptr++;
481 return ptr;
484 /***************************************************************************
485 * WCMD_keyword_ws_found
487 * Checks if the string located at ptr matches a keyword (of length len)
488 * followed by a whitespace character (space or tab)
490 BOOL WCMD_keyword_ws_found(const WCHAR *keyword, int len, const WCHAR *ptr) {
491 return (CompareStringW(LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
492 ptr, len, keyword, len) == CSTR_EQUAL)
493 && ((*(ptr + len) == ' ') || (*(ptr + len) == '\t'));
496 /*************************************************************************
497 * WCMD_strip_quotes
499 * Remove first and last quote WCHARacters, preserving all other text
500 * Returns the location of the final quote
502 WCHAR *WCMD_strip_quotes(WCHAR *cmd) {
503 WCHAR *src = cmd + 1, *dest = cmd, *lastq = NULL, *lastquote;
504 while((*dest=*src) != '\0') {
505 if (*src=='\"')
506 lastq=dest;
507 dest++, src++;
509 lastquote = lastq;
510 if (lastq) {
511 dest=lastq++;
512 while ((*dest++=*lastq++) != 0)
515 return lastquote;
519 /*************************************************************************
520 * WCMD_is_magic_envvar
521 * Return TRUE if s is '%'magicvar'%'
522 * and is not masked by a real environment variable.
525 static inline BOOL WCMD_is_magic_envvar(const WCHAR *s, const WCHAR *magicvar)
527 int len;
529 if (s[0] != '%')
530 return FALSE; /* Didn't begin with % */
531 len = strlenW(s);
532 if (len < 2 || s[len-1] != '%')
533 return FALSE; /* Didn't end with another % */
535 if (CompareStringW(LOCALE_USER_DEFAULT,
536 NORM_IGNORECASE | SORT_STRINGSORT,
537 s+1, len-2, magicvar, -1) != CSTR_EQUAL) {
538 /* Name doesn't match. */
539 return FALSE;
542 if (GetEnvironmentVariableW(magicvar, NULL, 0) > 0) {
543 /* Masked by real environment variable. */
544 return FALSE;
547 return TRUE;
550 /*************************************************************************
551 * WCMD_expand_envvar
553 * Expands environment variables, allowing for WCHARacter substitution
555 static WCHAR *WCMD_expand_envvar(WCHAR *start, WCHAR startchar)
557 WCHAR *endOfVar = NULL, *s;
558 WCHAR *colonpos = NULL;
559 WCHAR thisVar[MAXSTRING];
560 WCHAR thisVarContents[MAXSTRING];
561 WCHAR savedchar = 0x00;
562 int len;
564 static const WCHAR ErrorLvl[] = {'E','R','R','O','R','L','E','V','E','L','\0'};
565 static const WCHAR Date[] = {'D','A','T','E','\0'};
566 static const WCHAR Time[] = {'T','I','M','E','\0'};
567 static const WCHAR Cd[] = {'C','D','\0'};
568 static const WCHAR Random[] = {'R','A','N','D','O','M','\0'};
569 WCHAR Delims[] = {'%',':','\0'}; /* First char gets replaced appropriately */
571 WINE_TRACE("Expanding: %s (%c)\n", wine_dbgstr_w(start), startchar);
573 /* Find the end of the environment variable, and extract name */
574 Delims[0] = startchar;
575 endOfVar = strpbrkW(start+1, Delims);
577 if (endOfVar == NULL || *endOfVar==' ') {
579 /* In batch program, missing terminator for % and no following
580 ':' just removes the '%' */
581 if (context) {
582 WCMD_strsubstW(start, start + 1, NULL, 0);
583 return start;
584 } else {
586 /* In command processing, just ignore it - allows command line
587 syntax like: for %i in (a.a) do echo %i */
588 return start+1;
592 /* If ':' found, process remaining up until '%' (or stop at ':' if
593 a missing '%' */
594 if (*endOfVar==':') {
595 WCHAR *endOfVar2 = strchrW(endOfVar+1, startchar);
596 if (endOfVar2 != NULL) endOfVar = endOfVar2;
599 memcpy(thisVar, start, ((endOfVar - start) + 1) * sizeof(WCHAR));
600 thisVar[(endOfVar - start)+1] = 0x00;
601 colonpos = strchrW(thisVar+1, ':');
603 /* If there's complex substitution, just need %var% for now
604 to get the expanded data to play with */
605 if (colonpos) {
606 *colonpos = startchar;
607 savedchar = *(colonpos+1);
608 *(colonpos+1) = 0x00;
611 /* By now, we know the variable we want to expand but it may be
612 surrounded by '!' if we are in delayed expansion - if so convert
613 to % signs. */
614 if (startchar=='!') {
615 thisVar[0] = '%';
616 thisVar[(endOfVar - start)] = '%';
618 WINE_TRACE("Retrieving contents of %s\n", wine_dbgstr_w(thisVar));
620 /* Expand to contents, if unchanged, return */
621 /* Handle DATE, TIME, ERRORLEVEL and CD replacements allowing */
622 /* override if existing env var called that name */
623 if (WCMD_is_magic_envvar(thisVar, ErrorLvl)) {
624 static const WCHAR fmt[] = {'%','d','\0'};
625 wsprintfW(thisVarContents, fmt, errorlevel);
626 len = strlenW(thisVarContents);
627 } else if (WCMD_is_magic_envvar(thisVar, Date)) {
628 GetDateFormatW(LOCALE_USER_DEFAULT, DATE_SHORTDATE, NULL,
629 NULL, thisVarContents, MAXSTRING);
630 len = strlenW(thisVarContents);
631 } else if (WCMD_is_magic_envvar(thisVar, Time)) {
632 GetTimeFormatW(LOCALE_USER_DEFAULT, TIME_NOSECONDS, NULL,
633 NULL, thisVarContents, MAXSTRING);
634 len = strlenW(thisVarContents);
635 } else if (WCMD_is_magic_envvar(thisVar, Cd)) {
636 GetCurrentDirectoryW(MAXSTRING, thisVarContents);
637 len = strlenW(thisVarContents);
638 } else if (WCMD_is_magic_envvar(thisVar, Random)) {
639 static const WCHAR fmt[] = {'%','d','\0'};
640 wsprintfW(thisVarContents, fmt, rand() % 32768);
641 len = strlenW(thisVarContents);
642 } else {
644 len = ExpandEnvironmentStringsW(thisVar, thisVarContents,
645 sizeof(thisVarContents)/sizeof(WCHAR));
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 its 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 || (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_alloc(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 launched = FALSE;
1050 BOOL status;
1051 BOOL assumeInternal = FALSE;
1052 DWORD len;
1053 static const WCHAR envPath[] = {'P','A','T','H','\0'};
1054 static const WCHAR delims[] = {'/','\\',':','\0'};
1056 /* Quick way to get the filename is to extract the first argument. */
1057 WINE_TRACE("Running '%s' (%d)\n", wine_dbgstr_w(command), called);
1058 firstParam = WCMD_parameter(command, 0, NULL, FALSE, TRUE);
1059 if (!firstParam) return;
1061 /* Calculate the search path and stem to search for */
1062 if (strpbrkW (firstParam, delims) == NULL) { /* No explicit path given, search path */
1063 static const WCHAR curDir[] = {'.',';','\0'};
1064 strcpyW(pathtosearch, curDir);
1065 len = GetEnvironmentVariableW(envPath, &pathtosearch[2], (sizeof(pathtosearch)/sizeof(WCHAR))-2);
1066 if ((len == 0) || (len >= (sizeof(pathtosearch)/sizeof(WCHAR)) - 2)) {
1067 static const WCHAR curDir[] = {'.','\0'};
1068 strcpyW (pathtosearch, curDir);
1070 if (strchrW(firstParam, '.') != NULL) extensionsupplied = TRUE;
1071 if (strlenW(firstParam) >= MAX_PATH)
1073 WCMD_output_asis_stderr(WCMD_LoadMessage(WCMD_LINETOOLONG));
1074 return;
1077 strcpyW(stemofsearch, firstParam);
1079 } else {
1081 /* Convert eg. ..\fred to include a directory by removing file part */
1082 GetFullPathNameW(firstParam, sizeof(pathtosearch)/sizeof(WCHAR), pathtosearch, NULL);
1083 lastSlash = strrchrW(pathtosearch, '\\');
1084 if (lastSlash && strchrW(lastSlash, '.') != NULL) extensionsupplied = TRUE;
1085 strcpyW(stemofsearch, lastSlash+1);
1087 /* Reduce pathtosearch to a path with trailing '\' to support c:\a.bat and
1088 c:\windows\a.bat syntax */
1089 if (lastSlash) *(lastSlash + 1) = 0x00;
1092 /* Now extract PATHEXT */
1093 len = GetEnvironmentVariableW(envPathExt, pathext, sizeof(pathext)/sizeof(WCHAR));
1094 if ((len == 0) || (len >= (sizeof(pathext)/sizeof(WCHAR)))) {
1095 strcpyW (pathext, dfltPathExt);
1098 /* Loop through the search path, dir by dir */
1099 pathposn = pathtosearch;
1100 WINE_TRACE("Searching in '%s' for '%s'\n", wine_dbgstr_w(pathtosearch),
1101 wine_dbgstr_w(stemofsearch));
1102 while (!launched && pathposn) {
1104 WCHAR thisDir[MAX_PATH] = {'\0'};
1105 WCHAR *pos = NULL;
1106 BOOL found = FALSE;
1108 /* Work on the first directory on the search path */
1109 pos = strchrW(pathposn, ';');
1110 if (pos) {
1111 memcpy(thisDir, pathposn, (pos-pathposn) * sizeof(WCHAR));
1112 thisDir[(pos-pathposn)] = 0x00;
1113 pathposn = pos+1;
1115 } else {
1116 strcpyW(thisDir, pathposn);
1117 pathposn = NULL;
1120 /* Since you can have eg. ..\.. on the path, need to expand
1121 to full information */
1122 strcpyW(temp, thisDir);
1123 GetFullPathNameW(temp, MAX_PATH, thisDir, NULL);
1125 /* 1. If extension supplied, see if that file exists */
1126 strcatW(thisDir, slashW);
1127 strcatW(thisDir, stemofsearch);
1128 pos = &thisDir[strlenW(thisDir)]; /* Pos = end of name */
1130 /* 1. If extension supplied, see if that file exists */
1131 if (extensionsupplied) {
1132 if (GetFileAttributesW(thisDir) != INVALID_FILE_ATTRIBUTES) {
1133 found = TRUE;
1137 /* 2. Any .* matches? */
1138 if (!found) {
1139 HANDLE h;
1140 WIN32_FIND_DATAW finddata;
1141 static const WCHAR allFiles[] = {'.','*','\0'};
1143 strcatW(thisDir,allFiles);
1144 h = FindFirstFileW(thisDir, &finddata);
1145 FindClose(h);
1146 if (h != INVALID_HANDLE_VALUE) {
1148 WCHAR *thisExt = pathext;
1150 /* 3. Yes - Try each path ext */
1151 while (thisExt) {
1152 WCHAR *nextExt = strchrW(thisExt, ';');
1154 if (nextExt) {
1155 memcpy(pos, thisExt, (nextExt-thisExt) * sizeof(WCHAR));
1156 pos[(nextExt-thisExt)] = 0x00;
1157 thisExt = nextExt+1;
1158 } else {
1159 strcpyW(pos, thisExt);
1160 thisExt = NULL;
1163 if (GetFileAttributesW(thisDir) != INVALID_FILE_ATTRIBUTES) {
1164 found = TRUE;
1165 thisExt = NULL;
1171 /* Internal programs won't be picked up by this search, so even
1172 though not found, try one last createprocess and wait for it
1173 to complete.
1174 Note: Ideally we could tell between a console app (wait) and a
1175 windows app, but the API's for it fail in this case */
1176 if (!found && pathposn == NULL) {
1177 WINE_TRACE("ASSUMING INTERNAL\n");
1178 assumeInternal = TRUE;
1179 } else {
1180 WINE_TRACE("Found as %s\n", wine_dbgstr_w(thisDir));
1183 /* Once found, launch it */
1184 if (found || assumeInternal) {
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 /* Special case BAT and CMD */
1195 if (ext && (!strcmpiW(ext, batExt) || !strcmpiW(ext, cmdExt))) {
1196 BOOL oldinteractive = interactive;
1197 interactive = FALSE;
1198 WCMD_batch (thisDir, command, called, NULL, INVALID_HANDLE_VALUE);
1199 interactive = oldinteractive;
1200 return;
1201 } else {
1203 /* thisDir contains the file to be launched, but with what?
1204 eg. a.exe will require a.exe to be launched, a.html may be iexplore */
1205 hinst = FindExecutableW (thisDir, NULL, temp);
1206 if ((INT_PTR)hinst < 32)
1207 console = 0;
1208 else
1209 console = SHGetFileInfoW(temp, 0, &psfi, sizeof(psfi), SHGFI_EXETYPE);
1211 ZeroMemory (&st, sizeof(STARTUPINFOW));
1212 st.cb = sizeof(STARTUPINFOW);
1213 init_msvcrt_io_block(&st);
1215 /* Launch the process and if a CUI wait on it to complete
1216 Note: Launching internal wine processes cannot specify a full path to exe */
1217 status = CreateProcessW(assumeInternal?NULL : thisDir,
1218 command, NULL, NULL, TRUE, 0, NULL, NULL, &st, &pe);
1219 heap_free(st.lpReserved2);
1220 if ((opt_c || opt_k) && !opt_s && !status
1221 && GetLastError()==ERROR_FILE_NOT_FOUND && command[0]=='\"') {
1222 /* strip first and last quote WCHARacters and try again */
1223 WCMD_strip_quotes(command);
1224 opt_s = TRUE;
1225 WCMD_run_program(command, called);
1226 return;
1229 if (!status)
1230 break;
1232 /* Always wait when non-interactive (cmd /c or in batch program),
1233 or for console applications */
1234 if (assumeInternal || !interactive || (console && !HIWORD(console)))
1235 WaitForSingleObject (pe.hProcess, INFINITE);
1236 GetExitCodeProcess (pe.hProcess, &errorlevel);
1237 if (errorlevel == STILL_ACTIVE) errorlevel = 0;
1239 CloseHandle(pe.hProcess);
1240 CloseHandle(pe.hThread);
1241 return;
1246 /* Not found anywhere - were we called? */
1247 if (called) {
1248 CMD_LIST *toExecute = NULL; /* Commands left to be executed */
1250 /* Parse the command string, without reading any more input */
1251 WCMD_ReadAndParseLine(command, &toExecute, INVALID_HANDLE_VALUE);
1252 WCMD_process_commands(toExecute, FALSE, called);
1253 WCMD_free_commands(toExecute);
1254 toExecute = NULL;
1255 return;
1258 /* Not found anywhere - give up */
1259 WCMD_output_stderr(WCMD_LoadMessage(WCMD_NO_COMMAND_FOUND), command);
1261 /* If a command fails to launch, it sets errorlevel 9009 - which
1262 does not seem to have any associated constant definition */
1263 errorlevel = 9009;
1264 return;
1268 /*****************************************************************************
1269 * Process one command. If the command is EXIT this routine does not return.
1270 * We will recurse through here executing batch files.
1271 * Note: If call is used to a non-existing program, we reparse the line and
1272 * try to run it as an internal command. 'retrycall' represents whether
1273 * we are attempting this retry.
1275 void WCMD_execute (const WCHAR *command, const WCHAR *redirects,
1276 CMD_LIST **cmdList, BOOL retrycall)
1278 WCHAR *cmd, *p, *redir;
1279 int status, i;
1280 DWORD count, creationDisposition;
1281 HANDLE h;
1282 WCHAR *whichcmd;
1283 SECURITY_ATTRIBUTES sa;
1284 WCHAR *new_cmd = NULL;
1285 WCHAR *new_redir = NULL;
1286 HANDLE old_stdhandles[3] = {GetStdHandle (STD_INPUT_HANDLE),
1287 GetStdHandle (STD_OUTPUT_HANDLE),
1288 GetStdHandle (STD_ERROR_HANDLE)};
1289 DWORD idx_stdhandles[3] = {STD_INPUT_HANDLE,
1290 STD_OUTPUT_HANDLE,
1291 STD_ERROR_HANDLE};
1292 BOOL prev_echo_mode, piped = FALSE;
1294 WINE_TRACE("command on entry:%s (%p)\n",
1295 wine_dbgstr_w(command), cmdList);
1297 /* If the next command is a pipe then we implement pipes by redirecting
1298 the output from this command to a temp file and input into the
1299 next command from that temp file.
1300 FIXME: Use of named pipes would make more sense here as currently this
1301 process has to finish before the next one can start but this requires
1302 a change to not wait for the first app to finish but rather the pipe */
1303 if (cmdList && (*cmdList)->nextcommand &&
1304 (*cmdList)->nextcommand->prevDelim == CMD_PIPE) {
1306 WCHAR temp_path[MAX_PATH];
1307 static const WCHAR cmdW[] = {'C','M','D','\0'};
1309 /* Remember piping is in action */
1310 WINE_TRACE("Output needs to be piped\n");
1311 piped = TRUE;
1313 /* Generate a unique temporary filename */
1314 GetTempPathW(sizeof(temp_path)/sizeof(WCHAR), temp_path);
1315 GetTempFileNameW(temp_path, cmdW, 0, (*cmdList)->nextcommand->pipeFile);
1316 WINE_TRACE("Using temporary file of %s\n",
1317 wine_dbgstr_w((*cmdList)->nextcommand->pipeFile));
1320 /* Move copy of the command onto the heap so it can be expanded */
1321 new_cmd = heap_alloc(MAXSTRING * sizeof(WCHAR));
1322 strcpyW(new_cmd, command);
1324 /* Move copy of the redirects onto the heap so it can be expanded */
1325 new_redir = heap_alloc(MAXSTRING * sizeof(WCHAR));
1327 /* If piped output, send stdout to the pipe by appending >filename to redirects */
1328 if (piped) {
1329 static const WCHAR redirOut[] = {'%','s',' ','>',' ','%','s','\0'};
1330 wsprintfW (new_redir, redirOut, redirects, (*cmdList)->nextcommand->pipeFile);
1331 WINE_TRACE("Redirects now %s\n", wine_dbgstr_w(new_redir));
1332 } else {
1333 strcpyW(new_redir, redirects);
1336 /* Expand variables in command line mode only (batch mode will
1337 be expanded as the line is read in, except for 'for' loops) */
1338 handleExpansion(new_cmd, (context != NULL), delayedsubst);
1339 handleExpansion(new_redir, (context != NULL), delayedsubst);
1340 cmd = new_cmd;
1343 * Changing default drive has to be handled as a special case.
1346 if ((cmd[1] == ':') && IsCharAlphaW(cmd[0]) && (strlenW(cmd) == 2)) {
1347 WCHAR envvar[5];
1348 WCHAR dir[MAX_PATH];
1350 /* According to MSDN CreateProcess docs, special env vars record
1351 the current directory on each drive, in the form =C:
1352 so see if one specified, and if so go back to it */
1353 strcpyW(envvar, equalW);
1354 strcatW(envvar, cmd);
1355 if (GetEnvironmentVariableW(envvar, dir, MAX_PATH) == 0) {
1356 static const WCHAR fmt[] = {'%','s','\\','\0'};
1357 wsprintfW(cmd, fmt, cmd);
1358 WINE_TRACE("No special directory settings, using dir of %s\n", wine_dbgstr_w(cmd));
1360 WINE_TRACE("Got directory %s as %s\n", wine_dbgstr_w(envvar), wine_dbgstr_w(cmd));
1361 status = SetCurrentDirectoryW(cmd);
1362 if (!status) WCMD_print_error ();
1363 heap_free(cmd );
1364 heap_free(new_redir);
1365 return;
1368 sa.nLength = sizeof(sa);
1369 sa.lpSecurityDescriptor = NULL;
1370 sa.bInheritHandle = TRUE;
1373 * Redirect stdin, stdout and/or stderr if required.
1376 /* STDIN could come from a preceding pipe, so delete on close if it does */
1377 if (cmdList && (*cmdList)->pipeFile[0] != 0x00) {
1378 WINE_TRACE("Input coming from %s\n", wine_dbgstr_w((*cmdList)->pipeFile));
1379 h = CreateFileW((*cmdList)->pipeFile, GENERIC_READ,
1380 FILE_SHARE_READ, &sa, OPEN_EXISTING,
1381 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE, NULL);
1382 if (h == INVALID_HANDLE_VALUE) {
1383 WCMD_print_error ();
1384 heap_free(cmd);
1385 heap_free(new_redir);
1386 return;
1388 SetStdHandle (STD_INPUT_HANDLE, h);
1390 /* No need to remember the temporary name any longer once opened */
1391 (*cmdList)->pipeFile[0] = 0x00;
1393 /* Otherwise STDIN could come from a '<' redirect */
1394 } else if ((p = strchrW(new_redir,'<')) != NULL) {
1395 h = CreateFileW(WCMD_parameter(++p, 0, NULL, FALSE, FALSE), GENERIC_READ, FILE_SHARE_READ,
1396 &sa, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
1397 if (h == INVALID_HANDLE_VALUE) {
1398 WCMD_print_error ();
1399 heap_free(cmd);
1400 heap_free(new_redir);
1401 return;
1403 SetStdHandle (STD_INPUT_HANDLE, h);
1406 /* Scan the whole command looking for > and 2> */
1407 redir = new_redir;
1408 while (redir != NULL && ((p = strchrW(redir,'>')) != NULL)) {
1409 int handle = 0;
1411 if (p > redir && (*(p-1)=='2'))
1412 handle = 2;
1413 else
1414 handle = 1;
1416 p++;
1417 if ('>' == *p) {
1418 creationDisposition = OPEN_ALWAYS;
1419 p++;
1421 else {
1422 creationDisposition = CREATE_ALWAYS;
1425 /* Add support for 2>&1 */
1426 redir = p;
1427 if (*p == '&') {
1428 int idx = *(p+1) - '0';
1430 if (DuplicateHandle(GetCurrentProcess(),
1431 GetStdHandle(idx_stdhandles[idx]),
1432 GetCurrentProcess(),
1434 0, TRUE, DUPLICATE_SAME_ACCESS) == 0) {
1435 WINE_FIXME("Duplicating handle failed with gle %d\n", GetLastError());
1437 WINE_TRACE("Redirect %d (%p) to %d (%p)\n", handle, GetStdHandle(idx_stdhandles[idx]), idx, h);
1439 } else {
1440 WCHAR *param = WCMD_parameter(p, 0, NULL, FALSE, FALSE);
1441 h = CreateFileW(param, GENERIC_WRITE, 0, &sa, creationDisposition,
1442 FILE_ATTRIBUTE_NORMAL, NULL);
1443 if (h == INVALID_HANDLE_VALUE) {
1444 WCMD_print_error ();
1445 heap_free(cmd);
1446 heap_free(new_redir);
1447 return;
1449 if (SetFilePointer (h, 0, NULL, FILE_END) ==
1450 INVALID_SET_FILE_POINTER) {
1451 WCMD_print_error ();
1453 WINE_TRACE("Redirect %d to '%s' (%p)\n", handle, wine_dbgstr_w(param), h);
1456 SetStdHandle (idx_stdhandles[handle], h);
1460 * Strip leading whitespaces, and a '@' if supplied
1462 whichcmd = WCMD_skip_leading_spaces(cmd);
1463 WINE_TRACE("Command: '%s'\n", wine_dbgstr_w(cmd));
1464 if (whichcmd[0] == '@') whichcmd++;
1467 * Check if the command entered is internal. If it is, pass the rest of the
1468 * line down to the command. If not try to run a program.
1471 count = 0;
1472 while (IsCharAlphaNumericW(whichcmd[count])) {
1473 count++;
1475 for (i=0; i<=WCMD_EXIT; i++) {
1476 if (CompareStringW(LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
1477 whichcmd, count, inbuilt[i], -1) == CSTR_EQUAL) break;
1479 p = WCMD_skip_leading_spaces (&whichcmd[count]);
1480 WCMD_parse (p, quals, param1, param2);
1481 WINE_TRACE("param1: %s, param2: %s\n", wine_dbgstr_w(param1), wine_dbgstr_w(param2));
1483 if (i <= WCMD_EXIT && (p[0] == '/') && (p[1] == '?')) {
1484 /* this is a help request for a builtin program */
1485 i = WCMD_HELP;
1486 memcpy(p, whichcmd, count * sizeof(WCHAR));
1487 p[count] = '\0';
1491 switch (i) {
1493 case WCMD_CALL:
1494 WCMD_call (p);
1495 break;
1496 case WCMD_CD:
1497 case WCMD_CHDIR:
1498 WCMD_setshow_default (p);
1499 break;
1500 case WCMD_CLS:
1501 WCMD_clear_screen ();
1502 break;
1503 case WCMD_COPY:
1504 WCMD_copy (p);
1505 break;
1506 case WCMD_CTTY:
1507 WCMD_change_tty ();
1508 break;
1509 case WCMD_DATE:
1510 WCMD_setshow_date ();
1511 break;
1512 case WCMD_DEL:
1513 case WCMD_ERASE:
1514 WCMD_delete (p);
1515 break;
1516 case WCMD_DIR:
1517 WCMD_directory (p);
1518 break;
1519 case WCMD_ECHO:
1520 WCMD_echo(&whichcmd[count]);
1521 break;
1522 case WCMD_GOTO:
1523 WCMD_goto (cmdList);
1524 break;
1525 case WCMD_HELP:
1526 WCMD_give_help (p);
1527 break;
1528 case WCMD_LABEL:
1529 WCMD_volume (TRUE, p);
1530 break;
1531 case WCMD_MD:
1532 case WCMD_MKDIR:
1533 WCMD_create_dir (p);
1534 break;
1535 case WCMD_MOVE:
1536 WCMD_move ();
1537 break;
1538 case WCMD_PATH:
1539 WCMD_setshow_path (p);
1540 break;
1541 case WCMD_PAUSE:
1542 WCMD_pause ();
1543 break;
1544 case WCMD_PROMPT:
1545 WCMD_setshow_prompt ();
1546 break;
1547 case WCMD_REM:
1548 break;
1549 case WCMD_REN:
1550 case WCMD_RENAME:
1551 WCMD_rename ();
1552 break;
1553 case WCMD_RD:
1554 case WCMD_RMDIR:
1555 WCMD_remove_dir (p);
1556 break;
1557 case WCMD_SETLOCAL:
1558 WCMD_setlocal(p);
1559 break;
1560 case WCMD_ENDLOCAL:
1561 WCMD_endlocal();
1562 break;
1563 case WCMD_SET:
1564 WCMD_setshow_env (p);
1565 break;
1566 case WCMD_SHIFT:
1567 WCMD_shift (p);
1568 break;
1569 case WCMD_START:
1570 WCMD_start (p);
1571 break;
1572 case WCMD_TIME:
1573 WCMD_setshow_time ();
1574 break;
1575 case WCMD_TITLE:
1576 if (strlenW(&whichcmd[count]) > 0)
1577 WCMD_title(&whichcmd[count+1]);
1578 break;
1579 case WCMD_TYPE:
1580 WCMD_type (p);
1581 break;
1582 case WCMD_VER:
1583 WCMD_output_asis(newlineW);
1584 WCMD_version ();
1585 break;
1586 case WCMD_VERIFY:
1587 WCMD_verify (p);
1588 break;
1589 case WCMD_VOL:
1590 WCMD_volume (FALSE, p);
1591 break;
1592 case WCMD_PUSHD:
1593 WCMD_pushd(p);
1594 break;
1595 case WCMD_POPD:
1596 WCMD_popd();
1597 break;
1598 case WCMD_ASSOC:
1599 WCMD_assoc(p, TRUE);
1600 break;
1601 case WCMD_COLOR:
1602 WCMD_color();
1603 break;
1604 case WCMD_FTYPE:
1605 WCMD_assoc(p, FALSE);
1606 break;
1607 case WCMD_MORE:
1608 WCMD_more(p);
1609 break;
1610 case WCMD_CHOICE:
1611 WCMD_choice(p);
1612 break;
1613 case WCMD_EXIT:
1614 WCMD_exit (cmdList);
1615 break;
1616 case WCMD_FOR:
1617 case WCMD_IF:
1618 /* Very oddly, probably because of all the special parsing required for
1619 these two commands, neither for nor if are supported when called,
1620 ie call if 1==1... will fail. */
1621 if (!retrycall) {
1622 if (i==WCMD_FOR) WCMD_for (p, cmdList);
1623 else if (i==WCMD_IF) WCMD_if (p, cmdList);
1624 break;
1626 /* else: drop through */
1627 default:
1628 prev_echo_mode = echo_mode;
1629 WCMD_run_program (whichcmd, FALSE);
1630 echo_mode = prev_echo_mode;
1632 heap_free(cmd);
1633 heap_free(new_redir);
1635 /* Restore old handles */
1636 for (i=0; i<3; i++) {
1637 if (old_stdhandles[i] != GetStdHandle(idx_stdhandles[i])) {
1638 CloseHandle (GetStdHandle (idx_stdhandles[i]));
1639 SetStdHandle (idx_stdhandles[i], old_stdhandles[i]);
1644 /*************************************************************************
1645 * WCMD_LoadMessage
1646 * Load a string from the resource file, handling any error
1647 * Returns string retrieved from resource file
1649 WCHAR *WCMD_LoadMessage(UINT id) {
1650 static WCHAR msg[2048];
1651 static const WCHAR failedMsg[] = {'F','a','i','l','e','d','!','\0'};
1653 if (!LoadStringW(GetModuleHandleW(NULL), id, msg, sizeof(msg)/sizeof(WCHAR))) {
1654 WINE_FIXME("LoadString failed with %d\n", GetLastError());
1655 strcpyW(msg, failedMsg);
1657 return msg;
1660 /***************************************************************************
1661 * WCMD_DumpCommands
1663 * Dumps out the parsed command line to ensure syntax is correct
1665 static void WCMD_DumpCommands(CMD_LIST *commands) {
1666 CMD_LIST *thisCmd = commands;
1668 WINE_TRACE("Parsed line:\n");
1669 while (thisCmd != NULL) {
1670 WINE_TRACE("%p %d %2.2d %p %s Redir:%s\n",
1671 thisCmd,
1672 thisCmd->prevDelim,
1673 thisCmd->bracketDepth,
1674 thisCmd->nextcommand,
1675 wine_dbgstr_w(thisCmd->command),
1676 wine_dbgstr_w(thisCmd->redirects));
1677 thisCmd = thisCmd->nextcommand;
1681 /***************************************************************************
1682 * WCMD_addCommand
1684 * Adds a command to the current command list
1686 static void WCMD_addCommand(WCHAR *command, int *commandLen,
1687 WCHAR *redirs, int *redirLen,
1688 WCHAR **copyTo, int **copyToLen,
1689 CMD_DELIMITERS prevDelim, int curDepth,
1690 CMD_LIST **lastEntry, CMD_LIST **output) {
1692 CMD_LIST *thisEntry = NULL;
1694 /* Allocate storage for command */
1695 thisEntry = heap_alloc(sizeof(CMD_LIST));
1697 /* Copy in the command */
1698 if (command) {
1699 thisEntry->command = heap_alloc((*commandLen+1) * sizeof(WCHAR));
1700 memcpy(thisEntry->command, command, *commandLen * sizeof(WCHAR));
1701 thisEntry->command[*commandLen] = 0x00;
1703 /* Copy in the redirects */
1704 thisEntry->redirects = heap_alloc((*redirLen+1) * sizeof(WCHAR));
1705 memcpy(thisEntry->redirects, redirs, *redirLen * sizeof(WCHAR));
1706 thisEntry->redirects[*redirLen] = 0x00;
1707 thisEntry->pipeFile[0] = 0x00;
1709 /* Reset the lengths */
1710 *commandLen = 0;
1711 *redirLen = 0;
1712 *copyToLen = commandLen;
1713 *copyTo = command;
1715 } else {
1716 thisEntry->command = NULL;
1717 thisEntry->redirects = NULL;
1718 thisEntry->pipeFile[0] = 0x00;
1721 /* Fill in other fields */
1722 thisEntry->nextcommand = NULL;
1723 thisEntry->prevDelim = prevDelim;
1724 thisEntry->bracketDepth = curDepth;
1725 if (*lastEntry) {
1726 (*lastEntry)->nextcommand = thisEntry;
1727 } else {
1728 *output = thisEntry;
1730 *lastEntry = thisEntry;
1734 /***************************************************************************
1735 * WCMD_IsEndQuote
1737 * Checks if the quote pointed to is the end-quote.
1739 * Quotes end if:
1741 * 1) The current parameter ends at EOL or at the beginning
1742 * of a redirection or pipe and not in a quote section.
1744 * 2) If the next character is a space and not in a quote section.
1746 * Returns TRUE if this is an end quote, and FALSE if it is not.
1749 static BOOL WCMD_IsEndQuote(const WCHAR *quote, int quoteIndex)
1751 int quoteCount = quoteIndex;
1752 int i;
1754 /* If we are not in a quoted section, then we are not an end-quote */
1755 if(quoteIndex == 0)
1757 return FALSE;
1760 /* Check how many quotes are left for this parameter */
1761 for(i=0;quote[i];i++)
1763 if(quote[i] == '"')
1765 quoteCount++;
1768 /* Quote counting ends at EOL, redirection, space or pipe if current quote is complete */
1769 else if(((quoteCount % 2) == 0)
1770 && ((quote[i] == '<') || (quote[i] == '>') || (quote[i] == '|') || (quote[i] == ' ')))
1772 break;
1776 /* If the quote is part of the last part of a series of quotes-on-quotes, then it must
1777 be an end-quote */
1778 if(quoteIndex >= (quoteCount / 2))
1780 return TRUE;
1783 /* No cigar */
1784 return FALSE;
1787 /***************************************************************************
1788 * WCMD_ReadAndParseLine
1790 * Either uses supplied input or
1791 * Reads a file from the handle, and then...
1792 * Parse the text buffer, splitting into separate commands
1793 * - unquoted && strings split 2 commands but the 2nd is flagged as
1794 * following an &&
1795 * - ( as the first character just ups the bracket depth
1796 * - unquoted ) when bracket depth > 0 terminates a bracket and
1797 * adds a CMD_LIST structure with null command
1798 * - Anything else gets put into the command string (including
1799 * redirects)
1801 WCHAR *WCMD_ReadAndParseLine(const WCHAR *optionalcmd, CMD_LIST **output, HANDLE readFrom)
1803 WCHAR *curPos;
1804 int inQuotes = 0;
1805 WCHAR curString[MAXSTRING];
1806 int curStringLen = 0;
1807 WCHAR curRedirs[MAXSTRING];
1808 int curRedirsLen = 0;
1809 WCHAR *curCopyTo;
1810 int *curLen;
1811 int curDepth = 0;
1812 CMD_LIST *lastEntry = NULL;
1813 CMD_DELIMITERS prevDelim = CMD_NONE;
1814 static WCHAR *extraSpace = NULL; /* Deliberately never freed */
1815 static const WCHAR remCmd[] = {'r','e','m'};
1816 static const WCHAR forCmd[] = {'f','o','r'};
1817 static const WCHAR ifCmd[] = {'i','f'};
1818 static const WCHAR ifElse[] = {'e','l','s','e'};
1819 BOOL inOneLine = FALSE;
1820 BOOL inFor = FALSE;
1821 BOOL inIn = FALSE;
1822 BOOL inIf = FALSE;
1823 BOOL inElse= FALSE;
1824 BOOL onlyWhiteSpace = FALSE;
1825 BOOL lastWasWhiteSpace = FALSE;
1826 BOOL lastWasDo = FALSE;
1827 BOOL lastWasIn = FALSE;
1828 BOOL lastWasElse = FALSE;
1829 BOOL lastWasRedirect = TRUE;
1830 BOOL lastWasCaret = FALSE;
1832 /* Allocate working space for a command read from keyboard, file etc */
1833 if (!extraSpace)
1834 extraSpace = heap_alloc((MAXSTRING+1) * sizeof(WCHAR));
1835 if (!extraSpace)
1837 WINE_ERR("Could not allocate memory for extraSpace\n");
1838 return NULL;
1841 /* If initial command read in, use that, otherwise get input from handle */
1842 if (optionalcmd != NULL) {
1843 strcpyW(extraSpace, optionalcmd);
1844 } else if (readFrom == INVALID_HANDLE_VALUE) {
1845 WINE_FIXME("No command nor handle supplied\n");
1846 } else {
1847 if (!WCMD_fgets(extraSpace, MAXSTRING, readFrom))
1848 return NULL;
1850 curPos = extraSpace;
1852 /* Handle truncated input - issue warning */
1853 if (strlenW(extraSpace) == MAXSTRING -1) {
1854 WCMD_output_asis_stderr(WCMD_LoadMessage(WCMD_TRUNCATEDLINE));
1855 WCMD_output_asis_stderr(extraSpace);
1856 WCMD_output_asis_stderr(newlineW);
1859 /* Replace env vars if in a batch context */
1860 if (context) handleExpansion(extraSpace, FALSE, FALSE);
1862 /* Skip preceding whitespace */
1863 while (*curPos == ' ' || *curPos == '\t') curPos++;
1865 /* Show prompt before batch line IF echo is on and in batch program */
1866 if (context && echo_mode && *curPos && (*curPos != '@')) {
1867 static const WCHAR echoDot[] = {'e','c','h','o','.'};
1868 static const WCHAR echoCol[] = {'e','c','h','o',':'};
1869 const DWORD len = sizeof(echoDot)/sizeof(echoDot[0]);
1870 DWORD curr_size = strlenW(curPos);
1871 DWORD min_len = (curr_size < len ? curr_size : len);
1872 WCMD_show_prompt();
1873 WCMD_output_asis(curPos);
1874 /* I don't know why Windows puts a space here but it does */
1875 /* Except for lines starting with 'echo.' or 'echo:'. Ask MS why */
1876 if (CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
1877 curPos, min_len, echoDot, len) != CSTR_EQUAL
1878 && CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
1879 curPos, min_len, echoCol, len) != CSTR_EQUAL)
1881 WCMD_output_asis(spaceW);
1883 WCMD_output_asis(newlineW);
1886 /* Skip repeated 'no echo' characters */
1887 while (*curPos == '@') curPos++;
1889 /* Start with an empty string, copying to the command string */
1890 curStringLen = 0;
1891 curRedirsLen = 0;
1892 curCopyTo = curString;
1893 curLen = &curStringLen;
1894 lastWasRedirect = FALSE; /* Required e.g. for spaces between > and filename */
1896 /* Parse every character on the line being processed */
1897 while (*curPos != 0x00) {
1899 WCHAR thisChar;
1901 /* Debugging AID:
1902 WINE_TRACE("Looking at '%c' (len:%d, lws:%d, ows:%d)\n", *curPos, *curLen,
1903 lastWasWhiteSpace, onlyWhiteSpace);
1906 /* Prevent overflow caused by the caret escape char */
1907 if (*curLen >= MAXSTRING) {
1908 WINE_ERR("Overflow detected in command\n");
1909 return NULL;
1912 /* Certain commands need special handling */
1913 if (curStringLen == 0 && curCopyTo == curString) {
1914 static const WCHAR forDO[] = {'d','o'};
1916 /* If command starts with 'rem ' or identifies a label, ignore any &&, ( etc. */
1917 if (WCMD_keyword_ws_found(remCmd, sizeof(remCmd)/sizeof(remCmd[0]), curPos) ||
1918 *curPos == ':') {
1919 inOneLine = TRUE;
1921 } else if (WCMD_keyword_ws_found(forCmd, sizeof(forCmd)/sizeof(forCmd[0]), curPos)) {
1922 inFor = TRUE;
1924 /* If command starts with 'if ' or 'else ', handle ('s mid line. We should ensure this
1925 is only true in the command portion of the IF statement, but this
1926 should suffice for now
1927 FIXME: Silly syntax like "if 1(==1( (
1928 echo they equal
1929 )" will be parsed wrong */
1930 } else if (WCMD_keyword_ws_found(ifCmd, sizeof(ifCmd)/sizeof(ifCmd[0]), curPos)) {
1931 inIf = TRUE;
1933 } else if (WCMD_keyword_ws_found(ifElse, sizeof(ifElse)/sizeof(ifElse[0]), curPos)) {
1934 const int keyw_len = sizeof(ifElse)/sizeof(ifElse[0]) + 1;
1935 inElse = TRUE;
1936 lastWasElse = TRUE;
1937 onlyWhiteSpace = TRUE;
1938 memcpy(&curCopyTo[*curLen], curPos, keyw_len*sizeof(WCHAR));
1939 (*curLen)+=keyw_len;
1940 curPos+=keyw_len;
1941 continue;
1943 /* In a for loop, the DO command will follow a close bracket followed by
1944 whitespace, followed by DO, ie closeBracket inserts a NULL entry, curLen
1945 is then 0, and all whitespace is skipped */
1946 } else if (inFor &&
1947 WCMD_keyword_ws_found(forDO, sizeof(forDO)/sizeof(forDO[0]), curPos)) {
1948 const int keyw_len = sizeof(forDO)/sizeof(forDO[0]) + 1;
1949 WINE_TRACE("Found 'DO '\n");
1950 lastWasDo = TRUE;
1951 onlyWhiteSpace = TRUE;
1952 memcpy(&curCopyTo[*curLen], curPos, keyw_len*sizeof(WCHAR));
1953 (*curLen)+=keyw_len;
1954 curPos+=keyw_len;
1955 continue;
1957 } else if (curCopyTo == curString) {
1959 /* Special handling for the 'FOR' command */
1960 if (inFor && lastWasWhiteSpace) {
1961 static const WCHAR forIN[] = {'i','n'};
1963 WINE_TRACE("Found 'FOR ', comparing next parm: '%s'\n", wine_dbgstr_w(curPos));
1965 if (WCMD_keyword_ws_found(forIN, sizeof(forIN)/sizeof(forIN[0]), curPos)) {
1966 const int keyw_len = sizeof(forIN)/sizeof(forIN[0]) + 1;
1967 WINE_TRACE("Found 'IN '\n");
1968 lastWasIn = TRUE;
1969 onlyWhiteSpace = TRUE;
1970 memcpy(&curCopyTo[*curLen], curPos, keyw_len*sizeof(WCHAR));
1971 (*curLen)+=keyw_len;
1972 curPos+=keyw_len;
1973 continue;
1978 /* Nothing 'ends' a one line statement (e.g. REM or :labels mean
1979 the &&, quotes and redirection etc are ineffective, so just force
1980 the use of the default processing by skipping character specific
1981 matching below) */
1982 if (!inOneLine) thisChar = *curPos;
1983 else thisChar = 'X'; /* Character with no special processing */
1985 lastWasWhiteSpace = FALSE; /* Will be reset below */
1986 lastWasCaret = FALSE;
1988 switch (thisChar) {
1990 case '=': /* drop through - ignore token delimiters at the start of a command */
1991 case ',': /* drop through - ignore token delimiters at the start of a command */
1992 case '\t':/* drop through - ignore token delimiters at the start of a command */
1993 case ' ':
1994 /* If a redirect in place, it ends here */
1995 if (!inQuotes && !lastWasRedirect) {
1997 /* If finishing off a redirect, add a whitespace delimiter */
1998 if (curCopyTo == curRedirs) {
1999 curCopyTo[(*curLen)++] = ' ';
2001 curCopyTo = curString;
2002 curLen = &curStringLen;
2004 if (*curLen > 0) {
2005 curCopyTo[(*curLen)++] = *curPos;
2008 /* Remember just processed whitespace */
2009 lastWasWhiteSpace = TRUE;
2011 break;
2013 case '>': /* drop through - handle redirect chars the same */
2014 case '<':
2015 /* Make a redirect start here */
2016 if (!inQuotes) {
2017 curCopyTo = curRedirs;
2018 curLen = &curRedirsLen;
2019 lastWasRedirect = TRUE;
2022 /* See if 1>, 2> etc, in which case we have some patching up
2023 to do (provided there's a preceding whitespace, and enough
2024 chars read so far) */
2025 if (curStringLen > 2
2026 && (*(curPos-1)>='1') && (*(curPos-1)<='9')
2027 && ((*(curPos-2)==' ') || (*(curPos-2)=='\t'))) {
2028 curStringLen--;
2029 curString[curStringLen] = 0x00;
2030 curCopyTo[(*curLen)++] = *(curPos-1);
2033 curCopyTo[(*curLen)++] = *curPos;
2035 /* If a redirect is immediately followed by '&' (ie. 2>&1) then
2036 do not process that ampersand as an AND operator */
2037 if (thisChar == '>' && *(curPos+1) == '&') {
2038 curCopyTo[(*curLen)++] = *(curPos+1);
2039 curPos++;
2041 break;
2043 case '|': /* Pipe character only if not || */
2044 if (!inQuotes) {
2045 lastWasRedirect = FALSE;
2047 /* Add an entry to the command list */
2048 if (curStringLen > 0) {
2050 /* Add the current command */
2051 WCMD_addCommand(curString, &curStringLen,
2052 curRedirs, &curRedirsLen,
2053 &curCopyTo, &curLen,
2054 prevDelim, curDepth,
2055 &lastEntry, output);
2059 if (*(curPos+1) == '|') {
2060 curPos++; /* Skip other | */
2061 prevDelim = CMD_ONFAILURE;
2062 } else {
2063 prevDelim = CMD_PIPE;
2065 } else {
2066 curCopyTo[(*curLen)++] = *curPos;
2068 break;
2070 case '"': if (WCMD_IsEndQuote(curPos, inQuotes)) {
2071 inQuotes--;
2072 } else {
2073 inQuotes++; /* Quotes within quotes are fun! */
2075 curCopyTo[(*curLen)++] = *curPos;
2076 lastWasRedirect = FALSE;
2077 break;
2079 case '(': /* If a '(' is the first non whitespace in a command portion
2080 ie start of line or just after &&, then we read until an
2081 unquoted ) is found */
2082 WINE_TRACE("Found '(' conditions: curLen(%d), inQ(%d), onlyWS(%d)"
2083 ", for(%d, In:%d, Do:%d)"
2084 ", if(%d, else:%d, lwe:%d)\n",
2085 *curLen, inQuotes,
2086 onlyWhiteSpace,
2087 inFor, lastWasIn, lastWasDo,
2088 inIf, inElse, lastWasElse);
2089 lastWasRedirect = FALSE;
2091 /* Ignore open brackets inside the for set */
2092 if (*curLen == 0 && !inIn) {
2093 curDepth++;
2095 /* If in quotes, ignore brackets */
2096 } else if (inQuotes) {
2097 curCopyTo[(*curLen)++] = *curPos;
2099 /* In a FOR loop, an unquoted '(' may occur straight after
2100 IN or DO
2101 In an IF statement just handle it regardless as we don't
2102 parse the operands
2103 In an ELSE statement, only allow it straight away after
2104 the ELSE and whitespace
2106 } else if (inIf ||
2107 (inElse && lastWasElse && onlyWhiteSpace) ||
2108 (inFor && (lastWasIn || lastWasDo) && onlyWhiteSpace)) {
2110 /* If entering into an 'IN', set inIn */
2111 if (inFor && lastWasIn && onlyWhiteSpace) {
2112 WINE_TRACE("Inside an IN\n");
2113 inIn = TRUE;
2116 /* Add the current command */
2117 WCMD_addCommand(curString, &curStringLen,
2118 curRedirs, &curRedirsLen,
2119 &curCopyTo, &curLen,
2120 prevDelim, curDepth,
2121 &lastEntry, output);
2123 curDepth++;
2124 } else {
2125 curCopyTo[(*curLen)++] = *curPos;
2127 break;
2129 case '^': if (!inQuotes) {
2130 /* If we reach the end of the input, we need to wait for more */
2131 if (*(curPos+1) == 0x00) {
2132 lastWasCaret = TRUE;
2133 WINE_TRACE("Caret found at end of line\n");
2134 break;
2136 curPos++;
2138 curCopyTo[(*curLen)++] = *curPos;
2139 break;
2141 case '&': if (!inQuotes) {
2142 lastWasRedirect = FALSE;
2144 /* Add an entry to the command list */
2145 if (curStringLen > 0) {
2147 /* Add the current command */
2148 WCMD_addCommand(curString, &curStringLen,
2149 curRedirs, &curRedirsLen,
2150 &curCopyTo, &curLen,
2151 prevDelim, curDepth,
2152 &lastEntry, output);
2156 if (*(curPos+1) == '&') {
2157 curPos++; /* Skip other & */
2158 prevDelim = CMD_ONSUCCESS;
2159 } else {
2160 prevDelim = CMD_NONE;
2162 } else {
2163 curCopyTo[(*curLen)++] = *curPos;
2165 break;
2167 case ')': if (!inQuotes && curDepth > 0) {
2168 lastWasRedirect = FALSE;
2170 /* Add the current command if there is one */
2171 if (curStringLen) {
2173 /* Add the current command */
2174 WCMD_addCommand(curString, &curStringLen,
2175 curRedirs, &curRedirsLen,
2176 &curCopyTo, &curLen,
2177 prevDelim, curDepth,
2178 &lastEntry, output);
2181 /* Add an empty entry to the command list */
2182 prevDelim = CMD_NONE;
2183 WCMD_addCommand(NULL, &curStringLen,
2184 curRedirs, &curRedirsLen,
2185 &curCopyTo, &curLen,
2186 prevDelim, curDepth,
2187 &lastEntry, output);
2188 curDepth--;
2190 /* Leave inIn if necessary */
2191 if (inIn) inIn = FALSE;
2192 } else {
2193 curCopyTo[(*curLen)++] = *curPos;
2195 break;
2196 default:
2197 lastWasRedirect = FALSE;
2198 curCopyTo[(*curLen)++] = *curPos;
2201 curPos++;
2203 /* At various times we need to know if we have only skipped whitespace,
2204 so reset this variable and then it will remain true until a non
2205 whitespace is found */
2206 if ((thisChar != ' ') && (thisChar != '\t') && (thisChar != '\n'))
2207 onlyWhiteSpace = FALSE;
2209 /* Flag end of interest in FOR DO and IN parms once something has been processed */
2210 if (!lastWasWhiteSpace) {
2211 lastWasIn = lastWasDo = FALSE;
2214 /* If we have reached the end, add this command into the list
2215 Do not add command to list if escape char ^ was last */
2216 if (*curPos == 0x00 && !lastWasCaret && *curLen > 0) {
2218 /* Add an entry to the command list */
2219 WCMD_addCommand(curString, &curStringLen,
2220 curRedirs, &curRedirsLen,
2221 &curCopyTo, &curLen,
2222 prevDelim, curDepth,
2223 &lastEntry, output);
2226 /* If we have reached the end of the string, see if bracketing or
2227 final caret is outstanding */
2228 if (*curPos == 0x00 && (curDepth > 0 || lastWasCaret) &&
2229 readFrom != INVALID_HANDLE_VALUE) {
2230 WCHAR *extraData;
2232 WINE_TRACE("Need to read more data as outstanding brackets or carets\n");
2233 inOneLine = FALSE;
2234 prevDelim = CMD_NONE;
2235 inQuotes = 0;
2236 memset(extraSpace, 0x00, (MAXSTRING+1) * sizeof(WCHAR));
2237 extraData = extraSpace;
2239 /* Read more, skipping any blank lines */
2240 do {
2241 WINE_TRACE("Read more input\n");
2242 if (!context) WCMD_output_asis( WCMD_LoadMessage(WCMD_MOREPROMPT));
2243 if (!WCMD_fgets(extraData, MAXSTRING, readFrom))
2244 break;
2246 /* Edge case for carets - a completely blank line (i.e. was just
2247 CRLF) is oddly added as an LF but then more data is received (but
2248 only once more!) */
2249 if (lastWasCaret) {
2250 if (*extraSpace == 0x00) {
2251 WINE_TRACE("Read nothing, so appending LF char and will try again\n");
2252 *extraData++ = '\r';
2253 *extraData = 0x00;
2254 } else break;
2257 } while (*extraData == 0x00);
2258 curPos = extraSpace;
2259 if (context) handleExpansion(extraSpace, FALSE, FALSE);
2260 /* Continue to echo commands IF echo is on and in batch program */
2261 if (context && echo_mode && extraSpace[0] && (extraSpace[0] != '@')) {
2262 WCMD_output_asis(extraSpace);
2263 WCMD_output_asis(newlineW);
2268 /* Dump out the parsed output */
2269 WCMD_DumpCommands(*output);
2271 return extraSpace;
2274 /***************************************************************************
2275 * WCMD_process_commands
2277 * Process all the commands read in so far
2279 CMD_LIST *WCMD_process_commands(CMD_LIST *thisCmd, BOOL oneBracket,
2280 BOOL retrycall) {
2282 int bdepth = -1;
2284 if (thisCmd && oneBracket) bdepth = thisCmd->bracketDepth;
2286 /* Loop through the commands, processing them one by one */
2287 while (thisCmd) {
2289 CMD_LIST *origCmd = thisCmd;
2291 /* If processing one bracket only, and we find the end bracket
2292 entry (or less), return */
2293 if (oneBracket && !thisCmd->command &&
2294 bdepth <= thisCmd->bracketDepth) {
2295 WINE_TRACE("Finished bracket @ %p, next command is %p\n",
2296 thisCmd, thisCmd->nextcommand);
2297 return thisCmd->nextcommand;
2300 /* Ignore the NULL entries a ')' inserts (Only 'if' cares
2301 about them and it will be handled in there)
2302 Also, skip over any batch labels (eg. :fred) */
2303 if (thisCmd->command && thisCmd->command[0] != ':') {
2304 WINE_TRACE("Executing command: '%s'\n", wine_dbgstr_w(thisCmd->command));
2305 WCMD_execute (thisCmd->command, thisCmd->redirects, &thisCmd, retrycall);
2308 /* Step on unless the command itself already stepped on */
2309 if (thisCmd == origCmd) thisCmd = thisCmd->nextcommand;
2311 return NULL;
2314 /***************************************************************************
2315 * WCMD_free_commands
2317 * Frees the storage held for a parsed command line
2318 * - This is not done in the process_commands, as eventually the current
2319 * pointer will be modified within the commands, and hence a single free
2320 * routine is simpler
2322 void WCMD_free_commands(CMD_LIST *cmds) {
2324 /* Loop through the commands, freeing them one by one */
2325 while (cmds) {
2326 CMD_LIST *thisCmd = cmds;
2327 cmds = cmds->nextcommand;
2328 heap_free(thisCmd->command);
2329 heap_free(thisCmd->redirects);
2330 heap_free(thisCmd);
2335 /*****************************************************************************
2336 * Main entry point. This is a console application so we have a main() not a
2337 * winmain().
2340 int wmain (int argc, WCHAR *argvW[])
2342 int args;
2343 WCHAR *cmdLine = NULL;
2344 WCHAR *cmd = NULL;
2345 WCHAR *argPos = NULL;
2346 WCHAR string[1024];
2347 WCHAR envvar[4];
2348 BOOL opt_q;
2349 int opt_t = 0;
2350 static const WCHAR offW[] = {'O','F','F','\0'};
2351 static const WCHAR promptW[] = {'P','R','O','M','P','T','\0'};
2352 static const WCHAR defaultpromptW[] = {'$','P','$','G','\0'};
2353 CMD_LIST *toExecute = NULL; /* Commands left to be executed */
2354 OSVERSIONINFOW osv;
2355 char osver[50];
2357 srand(time(NULL));
2359 /* Get the windows version being emulated */
2360 osv.dwOSVersionInfoSize = sizeof(osv);
2361 GetVersionExW(&osv);
2363 /* Pre initialize some messages */
2364 strcpyW(anykey, WCMD_LoadMessage(WCMD_ANYKEY));
2365 sprintf(osver, "%d.%d.%d (%s)", osv.dwMajorVersion, osv.dwMinorVersion,
2366 osv.dwBuildNumber, PACKAGE_VERSION);
2367 cmd = WCMD_format_string(WCMD_LoadMessage(WCMD_VERSION), osver);
2368 strcpyW(version_string, cmd);
2369 LocalFree(cmd);
2370 cmd = NULL;
2372 /* Can't use argc/argv as it will have stripped quotes from parameters
2373 * meaning cmd.exe /C echo "quoted string" is impossible
2375 cmdLine = GetCommandLineW();
2376 WINE_TRACE("Full commandline '%s'\n", wine_dbgstr_w(cmdLine));
2377 args = 1; /* start at first arg, skipping cmd.exe itself */
2379 opt_c = opt_k = opt_q = opt_s = FALSE;
2380 WCMD_parameter(cmdLine, args, &argPos, TRUE, TRUE);
2381 while (argPos && argPos[0] != 0x00)
2383 WCHAR c;
2384 WINE_TRACE("Command line parm: '%s'\n", wine_dbgstr_w(argPos));
2385 if (argPos[0]!='/' || argPos[1]=='\0') {
2386 args++;
2387 WCMD_parameter(cmdLine, args, &argPos, TRUE, TRUE);
2388 continue;
2391 c=argPos[1];
2392 if (tolowerW(c)=='c') {
2393 opt_c = TRUE;
2394 } else if (tolowerW(c)=='q') {
2395 opt_q = TRUE;
2396 } else if (tolowerW(c)=='k') {
2397 opt_k = TRUE;
2398 } else if (tolowerW(c)=='s') {
2399 opt_s = TRUE;
2400 } else if (tolowerW(c)=='a') {
2401 unicodeOutput = FALSE;
2402 } else if (tolowerW(c)=='u') {
2403 unicodeOutput = TRUE;
2404 } else if (tolowerW(c)=='v' && argPos[2]==':') {
2405 delayedsubst = strncmpiW(&argPos[3], offW, 3);
2406 if (delayedsubst) WINE_TRACE("Delayed substitution is on\n");
2407 } else if (tolowerW(c)=='t' && argPos[2]==':') {
2408 opt_t=strtoulW(&argPos[3], NULL, 16);
2409 } else if (tolowerW(c)=='x' || tolowerW(c)=='y') {
2410 /* Ignored for compatibility with Windows */
2413 if (argPos[2]==0 || argPos[2]==' ' || argPos[2]=='\t' ||
2414 tolowerW(c)=='v') {
2415 args++;
2416 WCMD_parameter(cmdLine, args, &argPos, TRUE, TRUE);
2418 else /* handle `cmd /cnotepad.exe` and `cmd /x/c ...` */
2420 /* Do not step to next parameter, instead carry on parsing this one */
2421 argPos+=2;
2424 if (opt_c || opt_k) /* break out of parsing immediately after c or k */
2425 break;
2428 if (opt_q) {
2429 WCMD_echo(offW);
2432 /* Until we start to read from the keyboard, stay as non-interactive */
2433 interactive = FALSE;
2435 if (opt_c || opt_k) {
2436 int len;
2437 WCHAR *q1 = NULL,*q2 = NULL,*p;
2439 /* Handle very edge case error scenario, "cmd.exe /c" ie when there are no
2440 * parameters after the /C or /K by pretending there was a single space */
2441 if (argPos == NULL) argPos = (WCHAR *)spaceW;
2443 /* Take a copy */
2444 cmd = heap_strdupW(argPos);
2446 /* opt_s left unflagged if the command starts with and contains exactly
2447 * one quoted string (exactly two quote characters). The quoted string
2448 * must be an executable name that has whitespace and must not have the
2449 * following characters: &<>()@^| */
2451 if (!opt_s) {
2452 /* 1. Confirm there is at least one quote */
2453 q1 = strchrW(argPos, '"');
2454 if (!q1) opt_s=1;
2457 if (!opt_s) {
2458 /* 2. Confirm there is a second quote */
2459 q2 = strchrW(q1+1, '"');
2460 if (!q2) opt_s=1;
2463 if (!opt_s) {
2464 /* 3. Ensure there are no more quotes */
2465 if (strchrW(q2+1, '"')) opt_s=1;
2468 /* check first parameter for a space and invalid characters. There must not be any
2469 * invalid characters, but there must be one or more whitespace */
2470 if (!opt_s) {
2471 opt_s = TRUE;
2472 p=q1;
2473 while (p!=q2) {
2474 if (*p=='&' || *p=='<' || *p=='>' || *p=='(' || *p==')'
2475 || *p=='@' || *p=='^' || *p=='|') {
2476 opt_s = TRUE;
2477 break;
2479 if (*p==' ' || *p=='\t')
2480 opt_s = FALSE;
2481 p++;
2485 WINE_TRACE("/c command line: '%s'\n", wine_dbgstr_w(cmd));
2487 /* Finally, we only stay in new mode IF the first parameter is quoted and
2488 is a valid executable, i.e. must exist, otherwise drop back to old mode */
2489 if (!opt_s) {
2490 WCHAR *thisArg = WCMD_parameter(cmd, 0, NULL, FALSE, TRUE);
2491 WCHAR pathext[MAXSTRING];
2492 BOOL found = FALSE;
2494 /* Now extract PATHEXT */
2495 len = GetEnvironmentVariableW(envPathExt, pathext, sizeof(pathext)/sizeof(WCHAR));
2496 if ((len == 0) || (len >= (sizeof(pathext)/sizeof(WCHAR)))) {
2497 strcpyW (pathext, dfltPathExt);
2500 /* If the supplied parameter has any directory information, look there */
2501 WINE_TRACE("First parameter is '%s'\n", wine_dbgstr_w(thisArg));
2502 if (strchrW(thisArg, '\\') != NULL) {
2504 GetFullPathNameW(thisArg, sizeof(string)/sizeof(WCHAR), string, NULL);
2505 WINE_TRACE("Full path name '%s'\n", wine_dbgstr_w(string));
2506 p = string + strlenW(string);
2508 /* Does file exist with this name? */
2509 if (GetFileAttributesW(string) != INVALID_FILE_ATTRIBUTES) {
2510 WINE_TRACE("Found file as '%s'\n", wine_dbgstr_w(string));
2511 found = TRUE;
2512 } else {
2513 WCHAR *thisExt = pathext;
2515 /* No - try with each of the PATHEXT extensions */
2516 while (!found && thisExt) {
2517 WCHAR *nextExt = strchrW(thisExt, ';');
2519 if (nextExt) {
2520 memcpy(p, thisExt, (nextExt-thisExt) * sizeof(WCHAR));
2521 p[(nextExt-thisExt)] = 0x00;
2522 thisExt = nextExt+1;
2523 } else {
2524 strcpyW(p, thisExt);
2525 thisExt = NULL;
2528 /* Does file exist with this extension appended? */
2529 if (GetFileAttributesW(string) != INVALID_FILE_ATTRIBUTES) {
2530 WINE_TRACE("Found file as '%s'\n", wine_dbgstr_w(string));
2531 found = TRUE;
2536 /* Otherwise we now need to look in the path to see if we can find it */
2537 } else {
2538 p = thisArg + strlenW(thisArg);
2540 /* Does file exist with this name? */
2541 if (SearchPathW(NULL, thisArg, NULL, sizeof(string)/sizeof(WCHAR), string, NULL) != 0) {
2542 WINE_TRACE("Found on path as '%s'\n", wine_dbgstr_w(string));
2543 found = TRUE;
2544 } else {
2545 WCHAR *thisExt = pathext;
2547 /* No - try with each of the PATHEXT extensions */
2548 while (!found && thisExt) {
2549 WCHAR *nextExt = strchrW(thisExt, ';');
2551 if (nextExt) {
2552 *nextExt = 0;
2553 nextExt = nextExt+1;
2554 } else {
2555 nextExt = NULL;
2558 /* Does file exist with this extension? */
2559 if (SearchPathW(NULL, thisArg, thisExt, sizeof(string)/sizeof(WCHAR), string, NULL) != 0) {
2560 WINE_TRACE("Found on path as '%s' with extension '%s'\n", wine_dbgstr_w(string),
2561 wine_dbgstr_w(thisExt));
2562 found = TRUE;
2564 thisExt = nextExt;
2569 /* If not found, drop back to old behaviour */
2570 if (!found) {
2571 WINE_TRACE("Binary not found, dropping back to old behaviour\n");
2572 opt_s = TRUE;
2577 /* strip first and last quote characters if opt_s; check for invalid
2578 * executable is done later */
2579 if (opt_s && *cmd=='\"')
2580 WCMD_strip_quotes(cmd);
2583 /* Save cwd into appropriate env var (Must be before the /c processing */
2584 GetCurrentDirectoryW(sizeof(string)/sizeof(WCHAR), string);
2585 if (IsCharAlphaW(string[0]) && string[1] == ':') {
2586 static const WCHAR fmt[] = {'=','%','c',':','\0'};
2587 wsprintfW(envvar, fmt, string[0]);
2588 SetEnvironmentVariableW(envvar, string);
2589 WINE_TRACE("Set %s to %s\n", wine_dbgstr_w(envvar), wine_dbgstr_w(string));
2592 if (opt_c) {
2593 /* If we do a "cmd /c command", we don't want to allocate a new
2594 * console since the command returns immediately. Rather, we use
2595 * the currently allocated input and output handles. This allows
2596 * us to pipe to and read from the command interpreter.
2599 /* Parse the command string, without reading any more input */
2600 WCMD_ReadAndParseLine(cmd, &toExecute, INVALID_HANDLE_VALUE);
2601 WCMD_process_commands(toExecute, FALSE, FALSE);
2602 WCMD_free_commands(toExecute);
2603 toExecute = NULL;
2605 heap_free(cmd);
2606 return errorlevel;
2609 SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), ENABLE_LINE_INPUT |
2610 ENABLE_ECHO_INPUT | ENABLE_PROCESSED_INPUT);
2611 SetConsoleTitleW(WCMD_LoadMessage(WCMD_CONSTITLE));
2613 /* Note: cmd.exe /c dir does not get a new color, /k dir does */
2614 if (opt_t) {
2615 if (!(((opt_t & 0xF0) >> 4) == (opt_t & 0x0F))) {
2616 defaultColor = opt_t & 0xFF;
2617 param1[0] = 0x00;
2618 WCMD_color();
2620 } else {
2621 /* Check HKCU\Software\Microsoft\Command Processor
2622 Then HKLM\Software\Microsoft\Command Processor
2623 for defaultcolour value
2624 Note Can be supplied as DWORD or REG_SZ
2625 Note2 When supplied as REG_SZ it's in decimal!!! */
2626 HKEY key;
2627 DWORD type;
2628 DWORD value=0, size=4;
2629 static const WCHAR regKeyW[] = {'S','o','f','t','w','a','r','e','\\',
2630 'M','i','c','r','o','s','o','f','t','\\',
2631 'C','o','m','m','a','n','d',' ','P','r','o','c','e','s','s','o','r','\0'};
2632 static const WCHAR dfltColorW[] = {'D','e','f','a','u','l','t','C','o','l','o','r','\0'};
2634 if (RegOpenKeyExW(HKEY_CURRENT_USER, regKeyW,
2635 0, KEY_READ, &key) == ERROR_SUCCESS) {
2636 WCHAR strvalue[4];
2638 /* See if DWORD or REG_SZ */
2639 if (RegQueryValueExW(key, dfltColorW, NULL, &type,
2640 NULL, NULL) == ERROR_SUCCESS) {
2641 if (type == REG_DWORD) {
2642 size = sizeof(DWORD);
2643 RegQueryValueExW(key, dfltColorW, NULL, NULL,
2644 (LPBYTE)&value, &size);
2645 } else if (type == REG_SZ) {
2646 size = sizeof(strvalue)/sizeof(WCHAR);
2647 RegQueryValueExW(key, dfltColorW, NULL, NULL,
2648 (LPBYTE)strvalue, &size);
2649 value = strtoulW(strvalue, NULL, 10);
2652 RegCloseKey(key);
2655 if (value == 0 && RegOpenKeyExW(HKEY_LOCAL_MACHINE, regKeyW,
2656 0, KEY_READ, &key) == ERROR_SUCCESS) {
2657 WCHAR strvalue[4];
2659 /* See if DWORD or REG_SZ */
2660 if (RegQueryValueExW(key, dfltColorW, NULL, &type,
2661 NULL, NULL) == ERROR_SUCCESS) {
2662 if (type == REG_DWORD) {
2663 size = sizeof(DWORD);
2664 RegQueryValueExW(key, dfltColorW, NULL, NULL,
2665 (LPBYTE)&value, &size);
2666 } else if (type == REG_SZ) {
2667 size = sizeof(strvalue)/sizeof(WCHAR);
2668 RegQueryValueExW(key, dfltColorW, NULL, NULL,
2669 (LPBYTE)strvalue, &size);
2670 value = strtoulW(strvalue, NULL, 10);
2673 RegCloseKey(key);
2676 /* If one found, set the screen to that colour */
2677 if (!(((value & 0xF0) >> 4) == (value & 0x0F))) {
2678 defaultColor = value & 0xFF;
2679 param1[0] = 0x00;
2680 WCMD_color();
2685 if (opt_k) {
2686 /* Parse the command string, without reading any more input */
2687 WCMD_ReadAndParseLine(cmd, &toExecute, INVALID_HANDLE_VALUE);
2688 WCMD_process_commands(toExecute, FALSE, FALSE);
2689 WCMD_free_commands(toExecute);
2690 toExecute = NULL;
2691 heap_free(cmd);
2695 * Loop forever getting commands and executing them.
2698 SetEnvironmentVariableW(promptW, defaultpromptW);
2699 interactive = TRUE;
2700 if (!opt_k) WCMD_version ();
2701 while (TRUE) {
2703 /* Read until EOF (which for std input is never, but if redirect
2704 in place, may occur */
2705 if (echo_mode) WCMD_show_prompt();
2706 if (!WCMD_ReadAndParseLine(NULL, &toExecute, GetStdHandle(STD_INPUT_HANDLE)))
2707 break;
2708 WCMD_process_commands(toExecute, FALSE, FALSE);
2709 WCMD_free_commands(toExecute);
2710 toExecute = NULL;
2712 return 0;