winevulkan: Update to VK spec version 1.2.188.
[wine.git] / programs / cmd / wcmdmain.c
blobacf8f63b1f1a276cff1fc5e350fe7fa9583073d5
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 <time.h>
29 #include "wcmd.h"
30 #include "shellapi.h"
31 #include "wine/debug.h"
33 WINE_DEFAULT_DEBUG_CHANNEL(cmd);
35 extern const WCHAR inbuilt[][10];
36 extern struct env_stack *pushd_directories;
38 BATCH_CONTEXT *context = NULL;
39 DWORD errorlevel;
40 WCHAR quals[MAXSTRING], param1[MAXSTRING], param2[MAXSTRING];
41 BOOL interactive;
42 FOR_CONTEXT forloopcontext; /* The 'for' loop context */
43 BOOL delayedsubst = FALSE; /* The current delayed substitution setting */
45 int defaultColor = 7;
46 BOOL echo_mode = TRUE;
48 WCHAR anykey[100], version_string[100];
50 static BOOL opt_c, opt_k, opt_s, unicodeOutput = FALSE;
52 /* Variables pertaining to paging */
53 static BOOL paged_mode;
54 static const WCHAR *pagedMessage = NULL;
55 static int line_count;
56 static int max_height;
57 static int max_width;
58 static int numChars;
60 #define MAX_WRITECONSOLE_SIZE 65535
63 * Returns a buffer for reading from/writing to file
64 * Never freed
66 static char *get_file_buffer(void)
68 static char *output_bufA = NULL;
69 if (!output_bufA)
70 output_bufA = heap_xalloc(MAX_WRITECONSOLE_SIZE);
71 return output_bufA;
74 /*******************************************************************
75 * WCMD_output_asis_len - send output to current standard output
77 * Output a formatted unicode string. Ideally this will go to the console
78 * and hence required WriteConsoleW to output it, however if file i/o is
79 * redirected, it needs to be WriteFile'd using OEM (not ANSI) format
81 static void WCMD_output_asis_len(const WCHAR *message, DWORD len, HANDLE device)
83 DWORD nOut= 0;
84 DWORD res = 0;
86 /* If nothing to write, return (MORE does this sometimes) */
87 if (!len) return;
89 /* Try to write as unicode assuming it is to a console */
90 res = WriteConsoleW(device, message, len, &nOut, NULL);
92 /* If writing to console fails, assume it's file
93 i/o so convert to OEM codepage and output */
94 if (!res) {
95 BOOL usedDefaultChar = FALSE;
96 DWORD convertedChars;
97 char *buffer;
99 if (!unicodeOutput) {
101 if (!(buffer = get_file_buffer()))
102 return;
104 /* Convert to OEM, then output */
105 convertedChars = WideCharToMultiByte(GetConsoleOutputCP(), 0, message,
106 len, buffer, MAX_WRITECONSOLE_SIZE,
107 "?", &usedDefaultChar);
108 WriteFile(device, buffer, convertedChars,
109 &nOut, FALSE);
110 } else {
111 WriteFile(device, message, len*sizeof(WCHAR),
112 &nOut, FALSE);
115 return;
118 /*******************************************************************
119 * WCMD_output - send output to current standard output device.
123 void WINAPIV WCMD_output (const WCHAR *format, ...) {
125 __ms_va_list ap;
126 WCHAR* string;
127 DWORD len;
129 __ms_va_start(ap,format);
130 string = NULL;
131 len = FormatMessageW(FORMAT_MESSAGE_FROM_STRING|FORMAT_MESSAGE_ALLOCATE_BUFFER,
132 format, 0, 0, (LPWSTR)&string, 0, &ap);
133 __ms_va_end(ap);
134 if (len == 0 && GetLastError() != ERROR_NO_WORK_DONE)
135 WINE_FIXME("Could not format string: le=%u, fmt=%s\n", GetLastError(), wine_dbgstr_w(format));
136 else
138 WCMD_output_asis_len(string, len, GetStdHandle(STD_OUTPUT_HANDLE));
139 LocalFree(string);
143 /*******************************************************************
144 * WCMD_output_stderr - send output to current standard error device.
148 void WINAPIV WCMD_output_stderr (const WCHAR *format, ...) {
150 __ms_va_list ap;
151 WCHAR* string;
152 DWORD len;
154 __ms_va_start(ap,format);
155 string = NULL;
156 len = FormatMessageW(FORMAT_MESSAGE_FROM_STRING|FORMAT_MESSAGE_ALLOCATE_BUFFER,
157 format, 0, 0, (LPWSTR)&string, 0, &ap);
158 __ms_va_end(ap);
159 if (len == 0 && GetLastError() != ERROR_NO_WORK_DONE)
160 WINE_FIXME("Could not format string: le=%u, fmt=%s\n", GetLastError(), wine_dbgstr_w(format));
161 else
163 WCMD_output_asis_len(string, len, GetStdHandle(STD_ERROR_HANDLE));
164 LocalFree(string);
168 /*******************************************************************
169 * WCMD_format_string - allocate a buffer and format a string
173 WCHAR* WINAPIV WCMD_format_string (const WCHAR *format, ...)
175 __ms_va_list ap;
176 WCHAR* string;
177 DWORD len;
179 __ms_va_start(ap,format);
180 len = FormatMessageW(FORMAT_MESSAGE_FROM_STRING|FORMAT_MESSAGE_ALLOCATE_BUFFER,
181 format, 0, 0, (LPWSTR)&string, 0, &ap);
182 __ms_va_end(ap);
183 if (len == 0 && GetLastError() != ERROR_NO_WORK_DONE) {
184 WINE_FIXME("Could not format string: le=%u, fmt=%s\n", GetLastError(), wine_dbgstr_w(format));
185 string = (WCHAR*)LocalAlloc(LMEM_FIXED, 2);
186 *string = 0;
188 return string;
191 void WCMD_enter_paged_mode(const WCHAR *msg)
193 CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
195 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &consoleInfo)) {
196 max_height = consoleInfo.dwSize.Y;
197 max_width = consoleInfo.dwSize.X;
198 } else {
199 max_height = 25;
200 max_width = 80;
202 paged_mode = TRUE;
203 line_count = 0;
204 numChars = 0;
205 pagedMessage = (msg==NULL)? anykey : msg;
208 void WCMD_leave_paged_mode(void)
210 paged_mode = FALSE;
211 pagedMessage = NULL;
214 /***************************************************************************
215 * WCMD_Readfile
217 * Read characters in from a console/file, returning result in Unicode
219 BOOL WCMD_ReadFile(const HANDLE hIn, WCHAR *intoBuf, const DWORD maxChars, LPDWORD charsRead)
221 DWORD numRead;
222 char *buffer;
224 /* Try to read from console as Unicode */
225 if (ReadConsoleW(hIn, intoBuf, maxChars, charsRead, NULL)) return TRUE;
227 /* We assume it's a file handle and read then convert from assumed OEM codepage */
228 if (!(buffer = get_file_buffer()))
229 return FALSE;
231 if (!ReadFile(hIn, buffer, maxChars, &numRead, NULL))
232 return FALSE;
234 *charsRead = MultiByteToWideChar(GetConsoleCP(), 0, buffer, numRead, intoBuf, maxChars);
236 return TRUE;
239 /*******************************************************************
240 * WCMD_output_asis_handle
242 * Send output to specified handle without formatting e.g. when message contains '%'
244 static void WCMD_output_asis_handle (DWORD std_handle, const WCHAR *message) {
245 DWORD count;
246 const WCHAR* ptr;
247 WCHAR string[1024];
248 HANDLE handle = GetStdHandle(std_handle);
250 if (paged_mode) {
251 do {
252 ptr = message;
253 while (*ptr && *ptr!='\n' && (numChars < max_width)) {
254 numChars++;
255 ptr++;
257 if (*ptr == '\n') ptr++;
258 WCMD_output_asis_len(message, ptr - message, handle);
259 numChars = 0;
260 if (++line_count >= max_height - 1) {
261 line_count = 0;
262 WCMD_output_asis_len(pagedMessage, lstrlenW(pagedMessage), handle);
263 WCMD_ReadFile(GetStdHandle(STD_INPUT_HANDLE), string, ARRAY_SIZE(string), &count);
265 } while (((message = ptr) != NULL) && (*ptr));
266 } else {
267 WCMD_output_asis_len(message, lstrlenW(message), handle);
271 /*******************************************************************
272 * WCMD_output_asis
274 * Send output to current standard output device, without formatting
275 * e.g. when message contains '%'
277 void WCMD_output_asis (const WCHAR *message) {
278 WCMD_output_asis_handle(STD_OUTPUT_HANDLE, message);
281 /*******************************************************************
282 * WCMD_output_asis_stderr
284 * Send output to current standard error device, without formatting
285 * e.g. when message contains '%'
287 void WCMD_output_asis_stderr (const WCHAR *message) {
288 WCMD_output_asis_handle(STD_ERROR_HANDLE, message);
291 /****************************************************************************
292 * WCMD_print_error
294 * Print the message for GetLastError
297 void WCMD_print_error (void) {
298 LPVOID lpMsgBuf;
299 DWORD error_code;
300 int status;
302 error_code = GetLastError ();
303 status = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
304 NULL, error_code, 0, (LPWSTR) &lpMsgBuf, 0, NULL);
305 if (!status) {
306 WINE_FIXME ("Cannot display message for error %d, status %d\n",
307 error_code, GetLastError());
308 return;
311 WCMD_output_asis_len(lpMsgBuf, lstrlenW(lpMsgBuf),
312 GetStdHandle(STD_ERROR_HANDLE));
313 LocalFree (lpMsgBuf);
314 WCMD_output_asis_len(L"\r\n", lstrlenW(L"\r\n"), GetStdHandle(STD_ERROR_HANDLE));
315 return;
318 /******************************************************************************
319 * WCMD_show_prompt
321 * Display the prompt on STDout
325 static void WCMD_show_prompt (BOOL newLine) {
327 int status;
328 WCHAR out_string[MAX_PATH], curdir[MAX_PATH], prompt_string[MAX_PATH];
329 WCHAR *p, *q;
330 DWORD len;
332 len = GetEnvironmentVariableW(L"PROMPT", prompt_string, ARRAY_SIZE(prompt_string));
333 if ((len == 0) || (len >= ARRAY_SIZE(prompt_string))) {
334 lstrcpyW(prompt_string, L"$P$G");
336 p = prompt_string;
337 q = out_string;
338 if (newLine) {
339 *q++ = '\r';
340 *q++ = '\n';
342 *q = '\0';
343 while (*p != '\0') {
344 if (*p != '$') {
345 *q++ = *p++;
346 *q = '\0';
348 else {
349 p++;
350 switch (toupper(*p)) {
351 case '$':
352 *q++ = '$';
353 break;
354 case 'A':
355 *q++ = '&';
356 break;
357 case 'B':
358 *q++ = '|';
359 break;
360 case 'C':
361 *q++ = '(';
362 break;
363 case 'D':
364 GetDateFormatW(LOCALE_USER_DEFAULT, DATE_SHORTDATE, NULL, NULL, q, MAX_PATH - (q - out_string));
365 while (*q) q++;
366 break;
367 case 'E':
368 *q++ = '\x1b';
369 break;
370 case 'F':
371 *q++ = ')';
372 break;
373 case 'G':
374 *q++ = '>';
375 break;
376 case 'H':
377 *q++ = '\b';
378 break;
379 case 'L':
380 *q++ = '<';
381 break;
382 case 'N':
383 status = GetCurrentDirectoryW(ARRAY_SIZE(curdir), curdir);
384 if (status) {
385 *q++ = curdir[0];
387 break;
388 case 'P':
389 status = GetCurrentDirectoryW(ARRAY_SIZE(curdir), curdir);
390 if (status) {
391 lstrcatW (q, curdir);
392 while (*q) q++;
394 break;
395 case 'Q':
396 *q++ = '=';
397 break;
398 case 'S':
399 *q++ = ' ';
400 break;
401 case 'T':
402 GetTimeFormatW(LOCALE_USER_DEFAULT, 0, NULL, NULL, q, MAX_PATH);
403 while (*q) q++;
404 break;
405 case 'V':
406 lstrcatW (q, version_string);
407 while (*q) q++;
408 break;
409 case '_':
410 *q++ = '\n';
411 break;
412 case '+':
413 if (pushd_directories) {
414 memset(q, '+', pushd_directories->u.stackdepth);
415 q = q + pushd_directories->u.stackdepth;
417 break;
419 p++;
420 *q = '\0';
423 WCMD_output_asis (out_string);
426 void *heap_xalloc(size_t size)
428 void *ret;
430 ret = heap_alloc(size);
431 if(!ret) {
432 ERR("Out of memory\n");
433 ExitProcess(1);
436 return ret;
439 /*************************************************************************
440 * WCMD_strsubstW
441 * Replaces a portion of a Unicode string with the specified string.
442 * It's up to the caller to ensure there is enough space in the
443 * destination buffer.
445 void WCMD_strsubstW(WCHAR *start, const WCHAR *next, const WCHAR *insert, int len) {
447 if (len < 0)
448 len=insert ? lstrlenW(insert) : 0;
449 if (start+len != next)
450 memmove(start+len, next, (lstrlenW(next) + 1) * sizeof(*next));
451 if (insert)
452 memcpy(start, insert, len * sizeof(*insert));
455 /***************************************************************************
456 * WCMD_skip_leading_spaces
458 * Return a pointer to the first non-whitespace character of string.
459 * Does not modify the input string.
461 WCHAR *WCMD_skip_leading_spaces (WCHAR *string) {
463 WCHAR *ptr;
465 ptr = string;
466 while (*ptr == ' ' || *ptr == '\t') ptr++;
467 return ptr;
470 /***************************************************************************
471 * WCMD_keyword_ws_found
473 * Checks if the string located at ptr matches a keyword (of length len)
474 * followed by a whitespace character (space or tab)
476 BOOL WCMD_keyword_ws_found(const WCHAR *keyword, const WCHAR *ptr) {
477 const int len = lstrlenW(keyword);
478 return (CompareStringW(LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
479 ptr, len, keyword, len) == CSTR_EQUAL)
480 && ((*(ptr + len) == ' ') || (*(ptr + len) == '\t'));
483 /*************************************************************************
484 * WCMD_strip_quotes
486 * Remove first and last quote WCHARacters, preserving all other text
487 * Returns the location of the final quote
489 WCHAR *WCMD_strip_quotes(WCHAR *cmd) {
490 WCHAR *src = cmd + 1, *dest = cmd, *lastq = NULL, *lastquote;
491 while((*dest=*src) != '\0') {
492 if (*src=='\"')
493 lastq=dest;
494 dest++; src++;
496 lastquote = lastq;
497 if (lastq) {
498 dest=lastq++;
499 while ((*dest++=*lastq++) != 0)
502 return lastquote;
506 /*************************************************************************
507 * WCMD_is_magic_envvar
508 * Return TRUE if s is '%'magicvar'%'
509 * and is not masked by a real environment variable.
512 static inline BOOL WCMD_is_magic_envvar(const WCHAR *s, const WCHAR *magicvar)
514 int len;
516 if (s[0] != '%')
517 return FALSE; /* Didn't begin with % */
518 len = lstrlenW(s);
519 if (len < 2 || s[len-1] != '%')
520 return FALSE; /* Didn't end with another % */
522 if (CompareStringW(LOCALE_USER_DEFAULT,
523 NORM_IGNORECASE | SORT_STRINGSORT,
524 s+1, len-2, magicvar, -1) != CSTR_EQUAL) {
525 /* Name doesn't match. */
526 return FALSE;
529 if (GetEnvironmentVariableW(magicvar, NULL, 0) > 0) {
530 /* Masked by real environment variable. */
531 return FALSE;
534 return TRUE;
537 /*************************************************************************
538 * WCMD_expand_envvar
540 * Expands environment variables, allowing for WCHARacter substitution
542 static WCHAR *WCMD_expand_envvar(WCHAR *start, WCHAR startchar)
544 WCHAR *endOfVar = NULL, *s;
545 WCHAR *colonpos = NULL;
546 WCHAR thisVar[MAXSTRING];
547 WCHAR thisVarContents[MAXSTRING];
548 WCHAR savedchar = 0x00;
549 int len;
550 WCHAR Delims[] = L"%:"; /* First char gets replaced appropriately */
552 WINE_TRACE("Expanding: %s (%c)\n", wine_dbgstr_w(start), startchar);
554 /* Find the end of the environment variable, and extract name */
555 Delims[0] = startchar;
556 endOfVar = wcspbrk(start+1, Delims);
558 if (endOfVar == NULL || *endOfVar==' ') {
560 /* In batch program, missing terminator for % and no following
561 ':' just removes the '%' */
562 if (context) {
563 WCMD_strsubstW(start, start + 1, NULL, 0);
564 return start;
565 } else {
567 /* In command processing, just ignore it - allows command line
568 syntax like: for %i in (a.a) do echo %i */
569 return start+1;
573 /* If ':' found, process remaining up until '%' (or stop at ':' if
574 a missing '%' */
575 if (*endOfVar==':') {
576 WCHAR *endOfVar2 = wcschr(endOfVar+1, startchar);
577 if (endOfVar2 != NULL) endOfVar = endOfVar2;
580 memcpy(thisVar, start, ((endOfVar - start) + 1) * sizeof(WCHAR));
581 thisVar[(endOfVar - start)+1] = 0x00;
582 colonpos = wcschr(thisVar+1, ':');
584 /* If there's complex substitution, just need %var% for now
585 to get the expanded data to play with */
586 if (colonpos) {
587 *colonpos = startchar;
588 savedchar = *(colonpos+1);
589 *(colonpos+1) = 0x00;
592 /* By now, we know the variable we want to expand but it may be
593 surrounded by '!' if we are in delayed expansion - if so convert
594 to % signs. */
595 if (startchar=='!') {
596 thisVar[0] = '%';
597 thisVar[(endOfVar - start)] = '%';
599 WINE_TRACE("Retrieving contents of %s\n", wine_dbgstr_w(thisVar));
601 /* Expand to contents, if unchanged, return */
602 /* Handle DATE, TIME, ERRORLEVEL and CD replacements allowing */
603 /* override if existing env var called that name */
604 if (WCMD_is_magic_envvar(thisVar, L"ERRORLEVEL")) {
605 wsprintfW(thisVarContents, L"%d", errorlevel);
606 len = lstrlenW(thisVarContents);
607 } else if (WCMD_is_magic_envvar(thisVar, L"DATE")) {
608 GetDateFormatW(LOCALE_USER_DEFAULT, DATE_SHORTDATE, NULL,
609 NULL, thisVarContents, MAXSTRING);
610 len = lstrlenW(thisVarContents);
611 } else if (WCMD_is_magic_envvar(thisVar, L"TIME")) {
612 GetTimeFormatW(LOCALE_USER_DEFAULT, TIME_NOSECONDS, NULL,
613 NULL, thisVarContents, MAXSTRING);
614 len = lstrlenW(thisVarContents);
615 } else if (WCMD_is_magic_envvar(thisVar, L"CD")) {
616 GetCurrentDirectoryW(MAXSTRING, thisVarContents);
617 len = lstrlenW(thisVarContents);
618 } else if (WCMD_is_magic_envvar(thisVar, L"RANDOM")) {
619 wsprintfW(thisVarContents, L"%d", rand() % 32768);
620 len = lstrlenW(thisVarContents);
621 } else {
623 len = ExpandEnvironmentStringsW(thisVar, thisVarContents, ARRAY_SIZE(thisVarContents));
626 if (len == 0)
627 return endOfVar+1;
629 /* In a batch program, unknown env vars are replaced with nothing,
630 note syntax %garbage:1,3% results in anything after the ':'
631 except the %
632 From the command line, you just get back what you entered */
633 if (lstrcmpiW(thisVar, thisVarContents) == 0) {
635 /* Restore the complex part after the compare */
636 if (colonpos) {
637 *colonpos = ':';
638 *(colonpos+1) = savedchar;
641 /* Command line - just ignore this */
642 if (context == NULL) return endOfVar+1;
645 /* Batch - replace unknown env var with nothing */
646 if (colonpos == NULL) {
647 WCMD_strsubstW(start, endOfVar + 1, NULL, 0);
648 } else {
649 len = lstrlenW(thisVar);
650 thisVar[len-1] = 0x00;
651 /* If %:...% supplied, : is retained */
652 if (colonpos == thisVar+1) {
653 WCMD_strsubstW(start, endOfVar + 1, colonpos, -1);
654 } else {
655 WCMD_strsubstW(start, endOfVar + 1, colonpos + 1, -1);
658 return start;
662 /* See if we need to do complex substitution (any ':'s), if not
663 then our work here is done */
664 if (colonpos == NULL) {
665 WCMD_strsubstW(start, endOfVar + 1, thisVarContents, -1);
666 return start;
669 /* Restore complex bit */
670 *colonpos = ':';
671 *(colonpos+1) = savedchar;
674 Handle complex substitutions:
675 xxx=yyy (replace xxx with yyy)
676 *xxx=yyy (replace up to and including xxx with yyy)
677 ~x (from x WCHARs in)
678 ~-x (from x WCHARs from the end)
679 ~x,y (from x WCHARs in for y WCHARacters)
680 ~x,-y (from x WCHARs in until y WCHARacters from the end)
683 /* ~ is substring manipulation */
684 if (savedchar == '~') {
686 int substrposition, substrlength = 0;
687 WCHAR *commapos = wcschr(colonpos+2, ',');
688 WCHAR *startCopy;
690 substrposition = wcstol(colonpos+2, NULL, 10);
691 if (commapos) substrlength = wcstol(commapos+1, NULL, 10);
693 /* Check bounds */
694 if (substrposition >= 0) {
695 startCopy = &thisVarContents[min(substrposition, len)];
696 } else {
697 startCopy = &thisVarContents[max(0, len+substrposition-1)];
700 if (commapos == NULL) {
701 /* Copy the lot */
702 WCMD_strsubstW(start, endOfVar + 1, startCopy, -1);
703 } else if (substrlength < 0) {
705 int copybytes = (len+substrlength-1)-(startCopy-thisVarContents);
706 if (copybytes > len) copybytes = len;
707 else if (copybytes < 0) copybytes = 0;
708 WCMD_strsubstW(start, endOfVar + 1, startCopy, copybytes);
709 } else {
710 substrlength = min(substrlength, len - (startCopy- thisVarContents + 1));
711 WCMD_strsubstW(start, endOfVar + 1, startCopy, substrlength);
714 /* search and replace manipulation */
715 } else {
716 WCHAR *equalspos = wcsstr(colonpos, L"=");
717 WCHAR *replacewith = equalspos+1;
718 WCHAR *found = NULL;
719 WCHAR *searchIn;
720 WCHAR *searchFor;
722 if (equalspos == NULL) return start+1;
723 s = heap_strdupW(endOfVar + 1);
725 /* Null terminate both strings */
726 thisVar[lstrlenW(thisVar)-1] = 0x00;
727 *equalspos = 0x00;
729 /* Since we need to be case insensitive, copy the 2 buffers */
730 searchIn = heap_strdupW(thisVarContents);
731 CharUpperBuffW(searchIn, lstrlenW(thisVarContents));
732 searchFor = heap_strdupW(colonpos+1);
733 CharUpperBuffW(searchFor, lstrlenW(colonpos+1));
735 /* Handle wildcard case */
736 if (*(colonpos+1) == '*') {
737 /* Search for string to replace */
738 found = wcsstr(searchIn, searchFor+1);
740 if (found) {
741 /* Do replacement */
742 lstrcpyW(start, replacewith);
743 lstrcatW(start, thisVarContents + (found-searchIn) + lstrlenW(searchFor+1));
744 lstrcatW(start, s);
745 } else {
746 /* Copy as is */
747 lstrcpyW(start, thisVarContents);
748 lstrcatW(start, s);
751 } else {
752 /* Loop replacing all instances */
753 WCHAR *lastFound = searchIn;
754 WCHAR *outputposn = start;
756 *start = 0x00;
757 while ((found = wcsstr(lastFound, searchFor))) {
758 lstrcpynW(outputposn,
759 thisVarContents + (lastFound-searchIn),
760 (found - lastFound)+1);
761 outputposn = outputposn + (found - lastFound);
762 lstrcatW(outputposn, replacewith);
763 outputposn = outputposn + lstrlenW(replacewith);
764 lastFound = found + lstrlenW(searchFor);
766 lstrcatW(outputposn,
767 thisVarContents + (lastFound-searchIn));
768 lstrcatW(outputposn, s);
770 heap_free(s);
771 heap_free(searchIn);
772 heap_free(searchFor);
774 return start;
777 /*****************************************************************************
778 * Expand the command. Native expands lines from batch programs as they are
779 * read in and not again, except for 'for' variable substitution.
780 * eg. As evidence, "echo %1 && shift && echo %1" or "echo %%path%%"
781 * atExecute is TRUE when the expansion is occurring as the command is executed
782 * rather than at parse time, i.e. delayed expansion and for loops need to be
783 * processed
785 static void handleExpansion(WCHAR *cmd, BOOL atExecute, BOOL delayed) {
787 /* For commands in a context (batch program): */
788 /* Expand environment variables in a batch file %{0-9} first */
789 /* including support for any ~ modifiers */
790 /* Additionally: */
791 /* Expand the DATE, TIME, CD, RANDOM and ERRORLEVEL special */
792 /* names allowing environment variable overrides */
793 /* NOTE: To support the %PATH:xxx% syntax, also perform */
794 /* manual expansion of environment variables here */
796 WCHAR *p = cmd;
797 WCHAR *t;
798 int i;
799 WCHAR *delayedp = NULL;
800 WCHAR startchar = '%';
801 WCHAR *normalp;
803 /* Display the FOR variables in effect */
804 for (i=0;i<52;i++) {
805 if (forloopcontext.variable[i]) {
806 WINE_TRACE("FOR variable context: %c = '%s'\n",
807 i<26?i+'a':(i-26)+'A',
808 wine_dbgstr_w(forloopcontext.variable[i]));
812 /* Find the next environment variable delimiter */
813 normalp = wcschr(p, '%');
814 if (delayed) delayedp = wcschr(p, '!');
815 if (!normalp) p = delayedp;
816 else if (!delayedp) p = normalp;
817 else p = min(p,delayedp);
818 if (p) startchar = *p;
820 while (p) {
822 WINE_TRACE("Translate command:%s %d (at: %s)\n",
823 wine_dbgstr_w(cmd), atExecute, wine_dbgstr_w(p));
824 i = *(p+1) - '0';
826 /* Don't touch %% unless it's in Batch */
827 if (!atExecute && *(p+1) == startchar) {
828 if (context) {
829 WCMD_strsubstW(p, p+1, NULL, 0);
831 p+=1;
833 /* Replace %~ modifications if in batch program */
834 } else if (*(p+1) == '~') {
835 WCMD_HandleTildeModifiers(&p, atExecute);
836 p++;
838 /* Replace use of %0...%9 if in batch program*/
839 } else if (!atExecute && context && (i >= 0) && (i <= 9) && startchar == '%') {
840 t = WCMD_parameter(context -> command, i + context -> shift_count[i],
841 NULL, TRUE, TRUE);
842 WCMD_strsubstW(p, p+2, t, -1);
844 /* Replace use of %* if in batch program*/
845 } else if (!atExecute && context && *(p+1)=='*' && startchar == '%') {
846 WCHAR *startOfParms = NULL;
847 WCHAR *thisParm = WCMD_parameter(context -> command, 0, &startOfParms, TRUE, TRUE);
848 if (startOfParms != NULL) {
849 startOfParms += lstrlenW(thisParm);
850 while (*startOfParms==' ' || *startOfParms == '\t') startOfParms++;
851 WCMD_strsubstW(p, p+2, startOfParms, -1);
852 } else
853 WCMD_strsubstW(p, p+2, NULL, 0);
855 } else {
856 int forvaridx = FOR_VAR_IDX(*(p+1));
857 if (startchar == '%' && forvaridx != -1 && forloopcontext.variable[forvaridx]) {
858 /* Replace the 2 characters, % and for variable character */
859 WCMD_strsubstW(p, p + 2, forloopcontext.variable[forvaridx], -1);
860 } else if (!atExecute || startchar == '!') {
861 p = WCMD_expand_envvar(p, startchar);
863 /* In a FOR loop, see if this is the variable to replace */
864 } else { /* Ignore %'s on second pass of batch program */
865 p++;
869 /* Find the next environment variable delimiter */
870 normalp = wcschr(p, '%');
871 if (delayed) delayedp = wcschr(p, '!');
872 if (!normalp) p = delayedp;
873 else if (!delayedp) p = normalp;
874 else p = min(p,delayedp);
875 if (p) startchar = *p;
878 return;
882 /*******************************************************************
883 * WCMD_parse - parse a command into parameters and qualifiers.
885 * On exit, all qualifiers are concatenated into q, the first string
886 * not beginning with "/" is in p1 and the
887 * second in p2. Any subsequent non-qualifier strings are lost.
888 * Parameters in quotes are handled.
890 static void WCMD_parse (const WCHAR *s, WCHAR *q, WCHAR *p1, WCHAR *p2)
892 int p = 0;
894 *q = *p1 = *p2 = '\0';
895 while (TRUE) {
896 switch (*s) {
897 case '/':
898 *q++ = *s++;
899 while ((*s != '\0') && (*s != ' ') && *s != '/') {
900 *q++ = towupper (*s++);
902 *q = '\0';
903 break;
904 case ' ':
905 case '\t':
906 s++;
907 break;
908 case '"':
909 s++;
910 while ((*s != '\0') && (*s != '"')) {
911 if (p == 0) *p1++ = *s++;
912 else if (p == 1) *p2++ = *s++;
913 else s++;
915 if (p == 0) *p1 = '\0';
916 if (p == 1) *p2 = '\0';
917 p++;
918 if (*s == '"') s++;
919 break;
920 case '\0':
921 return;
922 default:
923 while ((*s != '\0') && (*s != ' ') && (*s != '\t')
924 && (*s != '=') && (*s != ',') ) {
925 if (p == 0) *p1++ = *s++;
926 else if (p == 1) *p2++ = *s++;
927 else s++;
929 /* Skip concurrent parms */
930 while ((*s == ' ') || (*s == '\t') || (*s == '=') || (*s == ',') ) s++;
932 if (p == 0) *p1 = '\0';
933 if (p == 1) *p2 = '\0';
934 p++;
939 static void init_msvcrt_io_block(STARTUPINFOW* st)
941 STARTUPINFOW st_p;
942 /* fetch the parent MSVCRT info block if any, so that the child can use the
943 * same handles as its grand-father
945 st_p.cb = sizeof(STARTUPINFOW);
946 GetStartupInfoW(&st_p);
947 st->cbReserved2 = st_p.cbReserved2;
948 st->lpReserved2 = st_p.lpReserved2;
949 if (st_p.cbReserved2 && st_p.lpReserved2)
951 unsigned num = *(unsigned*)st_p.lpReserved2;
952 char* flags;
953 HANDLE* handles;
954 BYTE *ptr;
955 size_t sz;
957 /* Override the entries for fd 0,1,2 if we happened
958 * to change those std handles (this depends on the way cmd sets
959 * its new input & output handles)
961 sz = max(sizeof(unsigned) + (sizeof(char) + sizeof(HANDLE)) * 3, st_p.cbReserved2);
962 ptr = heap_xalloc(sz);
963 flags = (char*)(ptr + sizeof(unsigned));
964 handles = (HANDLE*)(flags + num * sizeof(char));
966 memcpy(ptr, st_p.lpReserved2, st_p.cbReserved2);
967 st->cbReserved2 = sz;
968 st->lpReserved2 = ptr;
970 #define WX_OPEN 0x01 /* see dlls/msvcrt/file.c */
971 if (num <= 0 || (flags[0] & WX_OPEN))
973 handles[0] = GetStdHandle(STD_INPUT_HANDLE);
974 flags[0] |= WX_OPEN;
976 if (num <= 1 || (flags[1] & WX_OPEN))
978 handles[1] = GetStdHandle(STD_OUTPUT_HANDLE);
979 flags[1] |= WX_OPEN;
981 if (num <= 2 || (flags[2] & WX_OPEN))
983 handles[2] = GetStdHandle(STD_ERROR_HANDLE);
984 flags[2] |= WX_OPEN;
986 #undef WX_OPEN
990 /******************************************************************************
991 * WCMD_run_program
993 * Execute a command line as an external program. Must allow recursion.
995 * Precedence:
996 * Manual testing under windows shows PATHEXT plays a key part in this,
997 * and the search algorithm and precedence appears to be as follows.
999 * Search locations:
1000 * If directory supplied on command, just use that directory
1001 * If extension supplied on command, look for that explicit name first
1002 * Otherwise, search in each directory on the path
1003 * Precedence:
1004 * If extension supplied on command, look for that explicit name first
1005 * Then look for supplied name .* (even if extension supplied, so
1006 * 'garbage.exe' will match 'garbage.exe.cmd')
1007 * If any found, cycle through PATHEXT looking for name.exe one by one
1008 * Launching
1009 * Once a match has been found, it is launched - Code currently uses
1010 * findexecutable to achieve this which is left untouched.
1011 * If an executable has not been found, and we were launched through
1012 * a call, we need to check if the command is an internal command,
1013 * so go back through wcmd_execute.
1016 void WCMD_run_program (WCHAR *command, BOOL called)
1018 WCHAR temp[MAX_PATH];
1019 WCHAR pathtosearch[MAXSTRING];
1020 WCHAR *pathposn;
1021 WCHAR stemofsearch[MAX_PATH]; /* maximum allowed executable name is
1022 MAX_PATH, including null character */
1023 WCHAR *lastSlash;
1024 WCHAR pathext[MAXSTRING];
1025 WCHAR *firstParam;
1026 BOOL extensionsupplied = FALSE;
1027 BOOL explicit_path = FALSE;
1028 BOOL status;
1029 DWORD len;
1031 /* Quick way to get the filename is to extract the first argument. */
1032 WINE_TRACE("Running '%s' (%d)\n", wine_dbgstr_w(command), called);
1033 firstParam = WCMD_parameter(command, 0, NULL, FALSE, TRUE);
1034 if (!firstParam) return;
1036 if (!firstParam[0]) {
1037 errorlevel = 0;
1038 return;
1041 /* Calculate the search path and stem to search for */
1042 if (wcspbrk(firstParam, L"/\\:") == NULL) { /* No explicit path given, search path */
1043 lstrcpyW(pathtosearch, L".;");
1044 len = GetEnvironmentVariableW(L"PATH", &pathtosearch[2], ARRAY_SIZE(pathtosearch)-2);
1045 if ((len == 0) || (len >= ARRAY_SIZE(pathtosearch) - 2)) {
1046 lstrcpyW(pathtosearch, L".");
1048 if (wcschr(firstParam, '.') != NULL) extensionsupplied = TRUE;
1049 if (lstrlenW(firstParam) >= MAX_PATH)
1051 WCMD_output_asis_stderr(WCMD_LoadMessage(WCMD_LINETOOLONG));
1052 return;
1055 lstrcpyW(stemofsearch, firstParam);
1057 } else {
1059 /* Convert eg. ..\fred to include a directory by removing file part */
1060 GetFullPathNameW(firstParam, ARRAY_SIZE(pathtosearch), pathtosearch, NULL);
1061 lastSlash = wcsrchr(pathtosearch, '\\');
1062 if (lastSlash && wcschr(lastSlash, '.') != NULL) extensionsupplied = TRUE;
1063 lstrcpyW(stemofsearch, lastSlash+1);
1065 /* Reduce pathtosearch to a path with trailing '\' to support c:\a.bat and
1066 c:\windows\a.bat syntax */
1067 if (lastSlash) *(lastSlash + 1) = 0x00;
1068 explicit_path = TRUE;
1071 /* Now extract PATHEXT */
1072 len = GetEnvironmentVariableW(L"PATHEXT", pathext, ARRAY_SIZE(pathext));
1073 if ((len == 0) || (len >= ARRAY_SIZE(pathext))) {
1074 lstrcpyW(pathext, L".bat;.com;.cmd;.exe");
1077 /* Loop through the search path, dir by dir */
1078 pathposn = pathtosearch;
1079 WINE_TRACE("Searching in '%s' for '%s'\n", wine_dbgstr_w(pathtosearch),
1080 wine_dbgstr_w(stemofsearch));
1081 while (pathposn) {
1082 WCHAR thisDir[MAX_PATH] = {'\0'};
1083 int length = 0;
1084 WCHAR *pos = NULL;
1085 BOOL found = FALSE;
1086 BOOL inside_quotes = FALSE;
1088 if (explicit_path)
1090 lstrcpyW(thisDir, pathposn);
1091 pathposn = NULL;
1093 else
1095 /* Work on the next directory on the search path */
1096 pos = pathposn;
1097 while ((inside_quotes || *pos != ';') && *pos != 0)
1099 if (*pos == '"')
1100 inside_quotes = !inside_quotes;
1101 pos++;
1104 if (*pos) /* Reached semicolon */
1106 memcpy(thisDir, pathposn, (pos-pathposn) * sizeof(WCHAR));
1107 thisDir[(pos-pathposn)] = 0x00;
1108 pathposn = pos+1;
1110 else /* Reached string end */
1112 lstrcpyW(thisDir, pathposn);
1113 pathposn = NULL;
1116 /* Remove quotes */
1117 length = lstrlenW(thisDir);
1118 if (thisDir[length - 1] == '"')
1119 thisDir[length - 1] = 0;
1121 if (*thisDir != '"')
1122 lstrcpyW(temp, thisDir);
1123 else
1124 lstrcpyW(temp, thisDir + 1);
1126 /* Since you can have eg. ..\.. on the path, need to expand
1127 to full information */
1128 GetFullPathNameW(temp, MAX_PATH, thisDir, NULL);
1131 /* 1. If extension supplied, see if that file exists */
1132 lstrcatW(thisDir, L"\\");
1133 lstrcatW(thisDir, stemofsearch);
1134 pos = &thisDir[lstrlenW(thisDir)]; /* Pos = end of name */
1136 /* 1. If extension supplied, see if that file exists */
1137 if (extensionsupplied) {
1138 if (GetFileAttributesW(thisDir) != INVALID_FILE_ATTRIBUTES) {
1139 found = TRUE;
1143 /* 2. Any .* matches? */
1144 if (!found) {
1145 HANDLE h;
1146 WIN32_FIND_DATAW finddata;
1148 lstrcatW(thisDir, L".*");
1149 h = FindFirstFileW(thisDir, &finddata);
1150 FindClose(h);
1151 if (h != INVALID_HANDLE_VALUE) {
1153 WCHAR *thisExt = pathext;
1155 /* 3. Yes - Try each path ext */
1156 while (thisExt) {
1157 WCHAR *nextExt = wcschr(thisExt, ';');
1159 if (nextExt) {
1160 memcpy(pos, thisExt, (nextExt-thisExt) * sizeof(WCHAR));
1161 pos[(nextExt-thisExt)] = 0x00;
1162 thisExt = nextExt+1;
1163 } else {
1164 lstrcpyW(pos, thisExt);
1165 thisExt = NULL;
1168 if (GetFileAttributesW(thisDir) != INVALID_FILE_ATTRIBUTES) {
1169 found = TRUE;
1170 thisExt = NULL;
1176 /* Once found, launch it */
1177 if (found) {
1178 STARTUPINFOW st;
1179 PROCESS_INFORMATION pe;
1180 SHFILEINFOW psfi;
1181 DWORD console;
1182 HINSTANCE hinst;
1183 WCHAR *ext = wcsrchr( thisDir, '.' );
1185 WINE_TRACE("Found as %s\n", wine_dbgstr_w(thisDir));
1187 /* Special case BAT and CMD */
1188 if (ext && (!wcsicmp(ext, L".bat") || !wcsicmp(ext, L".cmd"))) {
1189 BOOL oldinteractive = interactive;
1190 interactive = FALSE;
1191 WCMD_batch (thisDir, command, called, NULL, INVALID_HANDLE_VALUE);
1192 interactive = oldinteractive;
1193 return;
1194 } else {
1196 /* thisDir contains the file to be launched, but with what?
1197 eg. a.exe will require a.exe to be launched, a.html may be iexplore */
1198 hinst = FindExecutableW (thisDir, NULL, temp);
1199 if ((INT_PTR)hinst < 32)
1200 console = 0;
1201 else
1202 console = SHGetFileInfoW(temp, 0, &psfi, sizeof(psfi), SHGFI_EXETYPE);
1204 ZeroMemory (&st, sizeof(STARTUPINFOW));
1205 st.cb = sizeof(STARTUPINFOW);
1206 init_msvcrt_io_block(&st);
1208 /* Launch the process and if a CUI wait on it to complete
1209 Note: Launching internal wine processes cannot specify a full path to exe */
1210 status = CreateProcessW(thisDir,
1211 command, NULL, NULL, TRUE, 0, NULL, NULL, &st, &pe);
1212 heap_free(st.lpReserved2);
1213 if ((opt_c || opt_k) && !opt_s && !status
1214 && GetLastError()==ERROR_FILE_NOT_FOUND && command[0]=='\"') {
1215 /* strip first and last quote WCHARacters and try again */
1216 WCMD_strip_quotes(command);
1217 opt_s = TRUE;
1218 WCMD_run_program(command, called);
1219 return;
1222 if (!status)
1223 break;
1225 /* Always wait when non-interactive (cmd /c or in batch program),
1226 or for console applications */
1227 if (!interactive || (console && !HIWORD(console)))
1228 WaitForSingleObject (pe.hProcess, INFINITE);
1229 GetExitCodeProcess (pe.hProcess, &errorlevel);
1230 if (errorlevel == STILL_ACTIVE) errorlevel = 0;
1232 CloseHandle(pe.hProcess);
1233 CloseHandle(pe.hThread);
1234 return;
1239 /* Not found anywhere - were we called? */
1240 if (called) {
1241 CMD_LIST *toExecute = NULL; /* Commands left to be executed */
1243 /* Parse the command string, without reading any more input */
1244 WCMD_ReadAndParseLine(command, &toExecute, INVALID_HANDLE_VALUE);
1245 WCMD_process_commands(toExecute, FALSE, called);
1246 WCMD_free_commands(toExecute);
1247 toExecute = NULL;
1248 return;
1251 /* Not found anywhere - give up */
1252 WCMD_output_stderr(WCMD_LoadMessage(WCMD_NO_COMMAND_FOUND), command);
1254 /* If a command fails to launch, it sets errorlevel 9009 - which
1255 does not seem to have any associated constant definition */
1256 errorlevel = 9009;
1257 return;
1261 /*****************************************************************************
1262 * Process one command. If the command is EXIT this routine does not return.
1263 * We will recurse through here executing batch files.
1264 * Note: If call is used to a non-existing program, we reparse the line and
1265 * try to run it as an internal command. 'retrycall' represents whether
1266 * we are attempting this retry.
1268 void WCMD_execute (const WCHAR *command, const WCHAR *redirects,
1269 CMD_LIST **cmdList, BOOL retrycall)
1271 WCHAR *cmd, *parms_start, *redir;
1272 WCHAR *pos;
1273 int status, i, cmd_index;
1274 DWORD count, creationDisposition;
1275 HANDLE h;
1276 WCHAR *whichcmd;
1277 SECURITY_ATTRIBUTES sa;
1278 WCHAR *new_cmd = NULL;
1279 WCHAR *new_redir = NULL;
1280 HANDLE old_stdhandles[3] = {GetStdHandle (STD_INPUT_HANDLE),
1281 GetStdHandle (STD_OUTPUT_HANDLE),
1282 GetStdHandle (STD_ERROR_HANDLE)};
1283 DWORD idx_stdhandles[3] = {STD_INPUT_HANDLE,
1284 STD_OUTPUT_HANDLE,
1285 STD_ERROR_HANDLE};
1286 BOOL prev_echo_mode, piped = FALSE;
1288 WINE_TRACE("command on entry:%s (%p)\n",
1289 wine_dbgstr_w(command), cmdList);
1291 /* Move copy of the command onto the heap so it can be expanded */
1292 new_cmd = heap_xalloc(MAXSTRING * sizeof(WCHAR));
1293 lstrcpyW(new_cmd, command);
1294 cmd = new_cmd;
1296 /* Move copy of the redirects onto the heap so it can be expanded */
1297 new_redir = heap_xalloc(MAXSTRING * sizeof(WCHAR));
1298 redir = new_redir;
1300 /* Strip leading whitespaces, and a '@' if supplied */
1301 whichcmd = WCMD_skip_leading_spaces(cmd);
1302 WINE_TRACE("Command: '%s'\n", wine_dbgstr_w(cmd));
1303 if (whichcmd[0] == '@') whichcmd++;
1305 /* Check if the command entered is internal, and identify which one */
1306 count = 0;
1307 while (IsCharAlphaNumericW(whichcmd[count])) {
1308 count++;
1310 for (i=0; i<=WCMD_EXIT; i++) {
1311 if (CompareStringW(LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
1312 whichcmd, count, inbuilt[i], -1) == CSTR_EQUAL) break;
1314 cmd_index = i;
1315 parms_start = WCMD_skip_leading_spaces (&whichcmd[count]);
1317 /* If the next command is a pipe then we implement pipes by redirecting
1318 the output from this command to a temp file and input into the
1319 next command from that temp file.
1320 Note: Do not do this for a for or if statement as the pipe is for
1321 the individual statements, not the for or if itself.
1322 FIXME: Use of named pipes would make more sense here as currently this
1323 process has to finish before the next one can start but this requires
1324 a change to not wait for the first app to finish but rather the pipe */
1325 if (!(cmd_index == WCMD_FOR || cmd_index == WCMD_IF) &&
1326 cmdList && (*cmdList)->nextcommand &&
1327 (*cmdList)->nextcommand->prevDelim == CMD_PIPE) {
1329 WCHAR temp_path[MAX_PATH];
1331 /* Remember piping is in action */
1332 WINE_TRACE("Output needs to be piped\n");
1333 piped = TRUE;
1335 /* Generate a unique temporary filename */
1336 GetTempPathW(ARRAY_SIZE(temp_path), temp_path);
1337 GetTempFileNameW(temp_path, L"CMD", 0, (*cmdList)->nextcommand->pipeFile);
1338 WINE_TRACE("Using temporary file of %s\n",
1339 wine_dbgstr_w((*cmdList)->nextcommand->pipeFile));
1342 /* If piped output, send stdout to the pipe by appending >filename to redirects */
1343 if (piped) {
1344 wsprintfW (new_redir, L"%s > %s", redirects, (*cmdList)->nextcommand->pipeFile);
1345 WINE_TRACE("Redirects now %s\n", wine_dbgstr_w(new_redir));
1346 } else {
1347 lstrcpyW(new_redir, redirects);
1350 /* Expand variables in command line mode only (batch mode will
1351 be expanded as the line is read in, except for 'for' loops) */
1352 handleExpansion(new_cmd, (context != NULL), delayedsubst);
1353 handleExpansion(new_redir, (context != NULL), delayedsubst);
1356 * Changing default drive has to be handled as a special case, anything
1357 * else if it exists after whitespace is ignored
1360 if ((cmd[1] == ':') && IsCharAlphaW(cmd[0]) &&
1361 (!cmd[2] || cmd[2] == ' ' || cmd[2] == '\t')) {
1362 WCHAR envvar[5];
1363 WCHAR dir[MAX_PATH];
1365 /* Ignore potential garbage on the same line */
1366 cmd[2]=0x00;
1368 /* According to MSDN CreateProcess docs, special env vars record
1369 the current directory on each drive, in the form =C:
1370 so see if one specified, and if so go back to it */
1371 lstrcpyW(envvar, L"=");
1372 lstrcatW(envvar, cmd);
1373 if (GetEnvironmentVariableW(envvar, dir, MAX_PATH) == 0) {
1374 wsprintfW(cmd, L"%s\\", cmd);
1375 WINE_TRACE("No special directory settings, using dir of %s\n", wine_dbgstr_w(cmd));
1377 WINE_TRACE("Got directory %s as %s\n", wine_dbgstr_w(envvar), wine_dbgstr_w(cmd));
1378 status = SetCurrentDirectoryW(cmd);
1379 if (!status) WCMD_print_error ();
1380 heap_free(cmd );
1381 heap_free(new_redir);
1382 return;
1385 sa.nLength = sizeof(sa);
1386 sa.lpSecurityDescriptor = NULL;
1387 sa.bInheritHandle = TRUE;
1390 * Redirect stdin, stdout and/or stderr if required.
1391 * Note: Do not do this for a for or if statement as the pipe is for
1392 * the individual statements, not the for or if itself.
1394 if (!(cmd_index == WCMD_FOR || cmd_index == WCMD_IF)) {
1395 /* STDIN could come from a preceding pipe, so delete on close if it does */
1396 if (cmdList && (*cmdList)->pipeFile[0] != 0x00) {
1397 WINE_TRACE("Input coming from %s\n", wine_dbgstr_w((*cmdList)->pipeFile));
1398 h = CreateFileW((*cmdList)->pipeFile, GENERIC_READ,
1399 FILE_SHARE_READ | FILE_SHARE_WRITE, &sa, OPEN_EXISTING,
1400 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE, NULL);
1401 if (h == INVALID_HANDLE_VALUE) {
1402 WCMD_print_error ();
1403 heap_free(cmd);
1404 heap_free(new_redir);
1405 return;
1407 SetStdHandle (STD_INPUT_HANDLE, h);
1409 /* No need to remember the temporary name any longer once opened */
1410 (*cmdList)->pipeFile[0] = 0x00;
1412 /* Otherwise STDIN could come from a '<' redirect */
1413 } else if ((pos = wcschr(new_redir,'<')) != NULL) {
1414 h = CreateFileW(WCMD_parameter(++pos, 0, NULL, FALSE, FALSE), GENERIC_READ, FILE_SHARE_READ,
1415 &sa, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
1416 if (h == INVALID_HANDLE_VALUE) {
1417 WCMD_print_error ();
1418 heap_free(cmd);
1419 heap_free(new_redir);
1420 return;
1422 SetStdHandle (STD_INPUT_HANDLE, h);
1425 /* Scan the whole command looking for > and 2> */
1426 while (redir != NULL && ((pos = wcschr(redir,'>')) != NULL)) {
1427 int handle = 0;
1429 if (pos > redir && (*(pos-1)=='2'))
1430 handle = 2;
1431 else
1432 handle = 1;
1434 pos++;
1435 if ('>' == *pos) {
1436 creationDisposition = OPEN_ALWAYS;
1437 pos++;
1439 else {
1440 creationDisposition = CREATE_ALWAYS;
1443 /* Add support for 2>&1 */
1444 redir = pos;
1445 if (*pos == '&') {
1446 int idx = *(pos+1) - '0';
1448 if (DuplicateHandle(GetCurrentProcess(),
1449 GetStdHandle(idx_stdhandles[idx]),
1450 GetCurrentProcess(),
1452 0, TRUE, DUPLICATE_SAME_ACCESS) == 0) {
1453 WINE_FIXME("Duplicating handle failed with gle %d\n", GetLastError());
1455 WINE_TRACE("Redirect %d (%p) to %d (%p)\n", handle, GetStdHandle(idx_stdhandles[idx]), idx, h);
1457 } else {
1458 WCHAR *param = WCMD_parameter(pos, 0, NULL, FALSE, FALSE);
1459 h = CreateFileW(param, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_DELETE,
1460 &sa, creationDisposition, FILE_ATTRIBUTE_NORMAL, NULL);
1461 if (h == INVALID_HANDLE_VALUE) {
1462 WCMD_print_error ();
1463 heap_free(cmd);
1464 heap_free(new_redir);
1465 return;
1467 if (SetFilePointer (h, 0, NULL, FILE_END) ==
1468 INVALID_SET_FILE_POINTER) {
1469 WCMD_print_error ();
1471 WINE_TRACE("Redirect %d to '%s' (%p)\n", handle, wine_dbgstr_w(param), h);
1474 SetStdHandle (idx_stdhandles[handle], h);
1476 } else {
1477 WINE_TRACE("Not touching redirects for a FOR or IF command\n");
1479 WCMD_parse (parms_start, quals, param1, param2);
1480 WINE_TRACE("param1: %s, param2: %s\n", wine_dbgstr_w(param1), wine_dbgstr_w(param2));
1482 if (i <= WCMD_EXIT && (parms_start[0] == '/') && (parms_start[1] == '?')) {
1483 /* this is a help request for a builtin program */
1484 i = WCMD_HELP;
1485 memcpy(parms_start, whichcmd, count * sizeof(WCHAR));
1486 parms_start[count] = '\0';
1490 switch (i) {
1492 case WCMD_CALL:
1493 WCMD_call (parms_start);
1494 break;
1495 case WCMD_CD:
1496 case WCMD_CHDIR:
1497 WCMD_setshow_default (parms_start);
1498 break;
1499 case WCMD_CLS:
1500 WCMD_clear_screen ();
1501 break;
1502 case WCMD_COPY:
1503 WCMD_copy (parms_start);
1504 break;
1505 case WCMD_CTTY:
1506 WCMD_change_tty ();
1507 break;
1508 case WCMD_DATE:
1509 WCMD_setshow_date ();
1510 break;
1511 case WCMD_DEL:
1512 case WCMD_ERASE:
1513 WCMD_delete (parms_start);
1514 break;
1515 case WCMD_DIR:
1516 WCMD_directory (parms_start);
1517 break;
1518 case WCMD_ECHO:
1519 WCMD_echo(&whichcmd[count]);
1520 break;
1521 case WCMD_GOTO:
1522 WCMD_goto (cmdList);
1523 break;
1524 case WCMD_HELP:
1525 WCMD_give_help (parms_start);
1526 break;
1527 case WCMD_LABEL:
1528 WCMD_volume (TRUE, parms_start);
1529 break;
1530 case WCMD_MD:
1531 case WCMD_MKDIR:
1532 WCMD_create_dir (parms_start);
1533 break;
1534 case WCMD_MOVE:
1535 WCMD_move ();
1536 break;
1537 case WCMD_PATH:
1538 WCMD_setshow_path (parms_start);
1539 break;
1540 case WCMD_PAUSE:
1541 WCMD_pause ();
1542 break;
1543 case WCMD_PROMPT:
1544 WCMD_setshow_prompt ();
1545 break;
1546 case WCMD_REM:
1547 break;
1548 case WCMD_REN:
1549 case WCMD_RENAME:
1550 WCMD_rename ();
1551 break;
1552 case WCMD_RD:
1553 case WCMD_RMDIR:
1554 WCMD_remove_dir (parms_start);
1555 break;
1556 case WCMD_SETLOCAL:
1557 WCMD_setlocal(parms_start);
1558 break;
1559 case WCMD_ENDLOCAL:
1560 WCMD_endlocal();
1561 break;
1562 case WCMD_SET:
1563 WCMD_setshow_env (parms_start);
1564 break;
1565 case WCMD_SHIFT:
1566 WCMD_shift (parms_start);
1567 break;
1568 case WCMD_START:
1569 WCMD_start (parms_start);
1570 break;
1571 case WCMD_TIME:
1572 WCMD_setshow_time ();
1573 break;
1574 case WCMD_TITLE:
1575 if (lstrlenW(&whichcmd[count]) > 0)
1576 WCMD_title(&whichcmd[count+1]);
1577 break;
1578 case WCMD_TYPE:
1579 WCMD_type (parms_start);
1580 break;
1581 case WCMD_VER:
1582 WCMD_output_asis(L"\r\n");
1583 WCMD_version ();
1584 break;
1585 case WCMD_VERIFY:
1586 WCMD_verify (parms_start);
1587 break;
1588 case WCMD_VOL:
1589 WCMD_volume (FALSE, parms_start);
1590 break;
1591 case WCMD_PUSHD:
1592 WCMD_pushd(parms_start);
1593 break;
1594 case WCMD_POPD:
1595 WCMD_popd();
1596 break;
1597 case WCMD_ASSOC:
1598 WCMD_assoc(parms_start, TRUE);
1599 break;
1600 case WCMD_COLOR:
1601 WCMD_color();
1602 break;
1603 case WCMD_FTYPE:
1604 WCMD_assoc(parms_start, FALSE);
1605 break;
1606 case WCMD_MORE:
1607 WCMD_more(parms_start);
1608 break;
1609 case WCMD_CHOICE:
1610 WCMD_choice(parms_start);
1611 break;
1612 case WCMD_MKLINK:
1613 WCMD_mklink(parms_start);
1614 break;
1615 case WCMD_EXIT:
1616 WCMD_exit (cmdList);
1617 break;
1618 case WCMD_FOR:
1619 case WCMD_IF:
1620 /* Very oddly, probably because of all the special parsing required for
1621 these two commands, neither 'for' nor 'if' is supported when called,
1622 i.e. 'call if 1==1...' will fail. */
1623 if (!retrycall) {
1624 if (i==WCMD_FOR) WCMD_for (parms_start, cmdList);
1625 else if (i==WCMD_IF) WCMD_if (parms_start, cmdList);
1626 break;
1628 /* else: drop through */
1629 default:
1630 prev_echo_mode = echo_mode;
1631 WCMD_run_program (whichcmd, FALSE);
1632 echo_mode = prev_echo_mode;
1634 heap_free(cmd);
1635 heap_free(new_redir);
1637 /* Restore old handles */
1638 for (i=0; i<3; i++) {
1639 if (old_stdhandles[i] != GetStdHandle(idx_stdhandles[i])) {
1640 CloseHandle (GetStdHandle (idx_stdhandles[i]));
1641 SetStdHandle (idx_stdhandles[i], old_stdhandles[i]);
1646 /*************************************************************************
1647 * WCMD_LoadMessage
1648 * Load a string from the resource file, handling any error
1649 * Returns string retrieved from resource file
1651 WCHAR *WCMD_LoadMessage(UINT id) {
1652 static WCHAR msg[2048];
1654 if (!LoadStringW(GetModuleHandleW(NULL), id, msg, ARRAY_SIZE(msg))) {
1655 WINE_FIXME("LoadString failed with %d\n", GetLastError());
1656 lstrcpyW(msg, L"Failed!");
1658 return msg;
1661 /***************************************************************************
1662 * WCMD_DumpCommands
1664 * Dumps out the parsed command line to ensure syntax is correct
1666 static void WCMD_DumpCommands(CMD_LIST *commands) {
1667 CMD_LIST *thisCmd = commands;
1669 WINE_TRACE("Parsed line:\n");
1670 while (thisCmd != NULL) {
1671 WINE_TRACE("%p %d %2.2d %p %s Redir:%s\n",
1672 thisCmd,
1673 thisCmd->prevDelim,
1674 thisCmd->bracketDepth,
1675 thisCmd->nextcommand,
1676 wine_dbgstr_w(thisCmd->command),
1677 wine_dbgstr_w(thisCmd->redirects));
1678 thisCmd = thisCmd->nextcommand;
1682 /***************************************************************************
1683 * WCMD_addCommand
1685 * Adds a command to the current command list
1687 static void WCMD_addCommand(WCHAR *command, int *commandLen,
1688 WCHAR *redirs, int *redirLen,
1689 WCHAR **copyTo, int **copyToLen,
1690 CMD_DELIMITERS prevDelim, int curDepth,
1691 CMD_LIST **lastEntry, CMD_LIST **output) {
1693 CMD_LIST *thisEntry = NULL;
1695 /* Allocate storage for command */
1696 thisEntry = heap_xalloc(sizeof(CMD_LIST));
1698 /* Copy in the command */
1699 if (command) {
1700 thisEntry->command = heap_xalloc((*commandLen+1) * sizeof(WCHAR));
1701 memcpy(thisEntry->command, command, *commandLen * sizeof(WCHAR));
1702 thisEntry->command[*commandLen] = 0x00;
1704 /* Copy in the redirects */
1705 thisEntry->redirects = heap_xalloc((*redirLen+1) * sizeof(WCHAR));
1706 memcpy(thisEntry->redirects, redirs, *redirLen * sizeof(WCHAR));
1707 thisEntry->redirects[*redirLen] = 0x00;
1708 thisEntry->pipeFile[0] = 0x00;
1710 /* Reset the lengths */
1711 *commandLen = 0;
1712 *redirLen = 0;
1713 *copyToLen = commandLen;
1714 *copyTo = command;
1716 } else {
1717 thisEntry->command = NULL;
1718 thisEntry->redirects = NULL;
1719 thisEntry->pipeFile[0] = 0x00;
1722 /* Fill in other fields */
1723 thisEntry->nextcommand = NULL;
1724 thisEntry->prevDelim = prevDelim;
1725 thisEntry->bracketDepth = curDepth;
1726 if (*lastEntry) {
1727 (*lastEntry)->nextcommand = thisEntry;
1728 } else {
1729 *output = thisEntry;
1731 *lastEntry = thisEntry;
1735 /***************************************************************************
1736 * WCMD_IsEndQuote
1738 * Checks if the quote pointed to is the end-quote.
1740 * Quotes end if:
1742 * 1) The current parameter ends at EOL or at the beginning
1743 * of a redirection or pipe and not in a quote section.
1745 * 2) If the next character is a space and not in a quote section.
1747 * Returns TRUE if this is an end quote, and FALSE if it is not.
1750 static BOOL WCMD_IsEndQuote(const WCHAR *quote, int quoteIndex)
1752 int quoteCount = quoteIndex;
1753 int i;
1755 /* If we are not in a quoted section, then we are not an end-quote */
1756 if(quoteIndex == 0)
1758 return FALSE;
1761 /* Check how many quotes are left for this parameter */
1762 for(i=0;quote[i];i++)
1764 if(quote[i] == '"')
1766 quoteCount++;
1769 /* Quote counting ends at EOL, redirection, space or pipe if current quote is complete */
1770 else if(((quoteCount % 2) == 0)
1771 && ((quote[i] == '<') || (quote[i] == '>') || (quote[i] == '|') || (quote[i] == ' ') ||
1772 (quote[i] == '&')))
1774 break;
1778 /* If the quote is part of the last part of a series of quotes-on-quotes, then it must
1779 be an end-quote */
1780 if(quoteIndex >= (quoteCount / 2))
1782 return TRUE;
1785 /* No cigar */
1786 return FALSE;
1789 /***************************************************************************
1790 * WCMD_ReadAndParseLine
1792 * Either uses supplied input or
1793 * Reads a file from the handle, and then...
1794 * Parse the text buffer, splitting into separate commands
1795 * - unquoted && strings split 2 commands but the 2nd is flagged as
1796 * following an &&
1797 * - ( as the first character just ups the bracket depth
1798 * - unquoted ) when bracket depth > 0 terminates a bracket and
1799 * adds a CMD_LIST structure with null command
1800 * - Anything else gets put into the command string (including
1801 * redirects)
1803 WCHAR *WCMD_ReadAndParseLine(const WCHAR *optionalcmd, CMD_LIST **output, HANDLE readFrom)
1805 WCHAR *curPos;
1806 int inQuotes = 0;
1807 WCHAR curString[MAXSTRING];
1808 int curStringLen = 0;
1809 WCHAR curRedirs[MAXSTRING];
1810 int curRedirsLen = 0;
1811 WCHAR *curCopyTo;
1812 int *curLen;
1813 int curDepth = 0;
1814 CMD_LIST *lastEntry = NULL;
1815 CMD_DELIMITERS prevDelim = CMD_NONE;
1816 static WCHAR *extraSpace = NULL; /* Deliberately never freed */
1817 BOOL inOneLine = FALSE;
1818 BOOL inFor = FALSE;
1819 BOOL inIn = FALSE;
1820 BOOL inIf = FALSE;
1821 BOOL inElse= FALSE;
1822 BOOL onlyWhiteSpace = FALSE;
1823 BOOL lastWasWhiteSpace = FALSE;
1824 BOOL lastWasDo = FALSE;
1825 BOOL lastWasIn = FALSE;
1826 BOOL lastWasElse = FALSE;
1827 BOOL lastWasRedirect = TRUE;
1828 BOOL lastWasCaret = FALSE;
1829 BOOL ignoreBracket = FALSE; /* Some expressions after if (set) require */
1830 /* handling brackets as a normal character */
1831 int lineCurDepth; /* Bracket depth when line was read in */
1832 BOOL resetAtEndOfLine = FALSE; /* Do we need to reset curdepth at EOL */
1834 /* Allocate working space for a command read from keyboard, file etc */
1835 if (!extraSpace)
1836 extraSpace = heap_xalloc((MAXSTRING+1) * sizeof(WCHAR));
1837 if (!extraSpace)
1839 WINE_ERR("Could not allocate memory for extraSpace\n");
1840 return NULL;
1843 /* If initial command read in, use that, otherwise get input from handle */
1844 if (optionalcmd != NULL) {
1845 lstrcpyW(extraSpace, optionalcmd);
1846 } else if (readFrom == INVALID_HANDLE_VALUE) {
1847 WINE_FIXME("No command nor handle supplied\n");
1848 } else {
1849 if (!WCMD_fgets(extraSpace, MAXSTRING, readFrom))
1850 return NULL;
1852 curPos = extraSpace;
1854 /* Handle truncated input - issue warning */
1855 if (lstrlenW(extraSpace) == MAXSTRING -1) {
1856 WCMD_output_asis_stderr(WCMD_LoadMessage(WCMD_TRUNCATEDLINE));
1857 WCMD_output_asis_stderr(extraSpace);
1858 WCMD_output_asis_stderr(L"\r\n");
1861 /* Replace env vars if in a batch context */
1862 if (context) handleExpansion(extraSpace, FALSE, FALSE);
1864 /* Skip preceding whitespace */
1865 while (*curPos == ' ' || *curPos == '\t') curPos++;
1867 /* Show prompt before batch line IF echo is on and in batch program */
1868 if (context && echo_mode && *curPos && (*curPos != '@')) {
1869 const DWORD len = lstrlenW(L"echo.");
1870 DWORD curr_size = lstrlenW(curPos);
1871 DWORD min_len = (curr_size < len ? curr_size : len);
1872 WCMD_show_prompt(TRUE);
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.', 'echo:' or 'echo/'. Ask MS why */
1876 if (CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
1877 curPos, min_len, L"echo.", len) != CSTR_EQUAL
1878 && CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
1879 curPos, min_len, L"echo:", len) != CSTR_EQUAL
1880 && CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
1881 curPos, min_len, L"echo/", len) != CSTR_EQUAL)
1883 WCMD_output_asis(L" ");
1885 WCMD_output_asis(L"\r\n");
1888 /* Skip repeated 'no echo' characters */
1889 while (*curPos == '@') curPos++;
1891 /* Start with an empty string, copying to the command string */
1892 curStringLen = 0;
1893 curRedirsLen = 0;
1894 curCopyTo = curString;
1895 curLen = &curStringLen;
1896 lastWasRedirect = FALSE; /* Required e.g. for spaces between > and filename */
1897 lineCurDepth = curDepth; /* What was the curdepth at the beginning of the line */
1899 /* Parse every character on the line being processed */
1900 while (*curPos != 0x00) {
1902 WCHAR thisChar;
1904 /* Debugging AID:
1905 WINE_TRACE("Looking at '%c' (len:%d, lws:%d, ows:%d)\n", *curPos, *curLen,
1906 lastWasWhiteSpace, onlyWhiteSpace);
1909 /* Prevent overflow caused by the caret escape char */
1910 if (*curLen >= MAXSTRING) {
1911 WINE_ERR("Overflow detected in command\n");
1912 return NULL;
1915 /* Certain commands need special handling */
1916 if (curStringLen == 0 && curCopyTo == curString) {
1917 /* If command starts with 'rem ' or identifies a label, ignore any &&, ( etc. */
1918 if (WCMD_keyword_ws_found(L"rem", curPos) || *curPos == ':') {
1919 inOneLine = TRUE;
1921 } else if (WCMD_keyword_ws_found(L"for", 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 To be able to handle ('s in the condition part take as much as evaluate_if_condition
1928 would take and skip parsing it here. */
1929 } else if (WCMD_keyword_ws_found(L"if", curPos)) {
1930 int negate; /* Negate condition */
1931 int test; /* Condition evaluation result */
1932 WCHAR *p, *command;
1934 inIf = TRUE;
1936 p = curPos+(lstrlenW(L"if"));
1937 while (*p == ' ' || *p == '\t')
1938 p++;
1939 WCMD_parse (p, quals, param1, param2);
1941 /* Function evaluate_if_condition relies on the global variables quals, param1 and param2
1942 set in a call to WCMD_parse before */
1943 if (evaluate_if_condition(p, &command, &test, &negate) != -1)
1945 int if_condition_len = command - curPos;
1946 WINE_TRACE("p: %s, quals: %s, param1: %s, param2: %s, command: %s, if_condition_len: %d\n",
1947 wine_dbgstr_w(p), wine_dbgstr_w(quals), wine_dbgstr_w(param1),
1948 wine_dbgstr_w(param2), wine_dbgstr_w(command), if_condition_len);
1949 memcpy(&curCopyTo[*curLen], curPos, if_condition_len*sizeof(WCHAR));
1950 (*curLen)+=if_condition_len;
1951 curPos+=if_condition_len;
1954 if (WCMD_keyword_ws_found(L"set", curPos))
1955 ignoreBracket = TRUE;
1957 } else if (WCMD_keyword_ws_found(L"else", curPos)) {
1958 const int keyw_len = lstrlenW(L"else") + 1;
1959 inElse = TRUE;
1960 lastWasElse = TRUE;
1961 onlyWhiteSpace = TRUE;
1962 memcpy(&curCopyTo[*curLen], curPos, keyw_len*sizeof(WCHAR));
1963 (*curLen)+=keyw_len;
1964 curPos+=keyw_len;
1966 /* If we had a single line if XXX which reaches an else (needs odd
1967 syntax like if 1=1 command && (command) else command we pretended
1968 to add brackets for the if, so they are now over */
1969 if (resetAtEndOfLine) {
1970 WINE_TRACE("Resetting curdepth at end of line to %d\n", lineCurDepth);
1971 resetAtEndOfLine = FALSE;
1972 curDepth = lineCurDepth;
1974 continue;
1976 /* In a for loop, the DO command will follow a close bracket followed by
1977 whitespace, followed by DO, ie closeBracket inserts a NULL entry, curLen
1978 is then 0, and all whitespace is skipped */
1979 } else if (inFor && WCMD_keyword_ws_found(L"do", curPos)) {
1980 const int keyw_len = lstrlenW(L"do") + 1;
1981 WINE_TRACE("Found 'DO '\n");
1982 lastWasDo = TRUE;
1983 onlyWhiteSpace = TRUE;
1984 memcpy(&curCopyTo[*curLen], curPos, keyw_len*sizeof(WCHAR));
1985 (*curLen)+=keyw_len;
1986 curPos+=keyw_len;
1987 continue;
1989 } else if (curCopyTo == curString) {
1991 /* Special handling for the 'FOR' command */
1992 if (inFor && lastWasWhiteSpace) {
1993 WINE_TRACE("Found 'FOR ', comparing next parm: '%s'\n", wine_dbgstr_w(curPos));
1995 if (WCMD_keyword_ws_found(L"in", curPos)) {
1996 const int keyw_len = lstrlenW(L"in") + 1;
1997 WINE_TRACE("Found 'IN '\n");
1998 lastWasIn = TRUE;
1999 onlyWhiteSpace = TRUE;
2000 memcpy(&curCopyTo[*curLen], curPos, keyw_len*sizeof(WCHAR));
2001 (*curLen)+=keyw_len;
2002 curPos+=keyw_len;
2003 continue;
2008 /* Nothing 'ends' a one line statement (e.g. REM or :labels mean
2009 the &&, quotes and redirection etc are ineffective, so just force
2010 the use of the default processing by skipping character specific
2011 matching below) */
2012 if (!inOneLine) thisChar = *curPos;
2013 else thisChar = 'X'; /* Character with no special processing */
2015 lastWasWhiteSpace = FALSE; /* Will be reset below */
2016 lastWasCaret = FALSE;
2018 switch (thisChar) {
2020 case '=': /* drop through - ignore token delimiters at the start of a command */
2021 case ',': /* drop through - ignore token delimiters at the start of a command */
2022 case '\t':/* drop through - ignore token delimiters at the start of a command */
2023 case ' ':
2024 /* If a redirect in place, it ends here */
2025 if (!inQuotes && !lastWasRedirect) {
2027 /* If finishing off a redirect, add a whitespace delimiter */
2028 if (curCopyTo == curRedirs) {
2029 curCopyTo[(*curLen)++] = ' ';
2031 curCopyTo = curString;
2032 curLen = &curStringLen;
2034 if (*curLen > 0) {
2035 curCopyTo[(*curLen)++] = *curPos;
2038 /* Remember just processed whitespace */
2039 lastWasWhiteSpace = TRUE;
2041 break;
2043 case '>': /* drop through - handle redirect chars the same */
2044 case '<':
2045 /* Make a redirect start here */
2046 if (!inQuotes) {
2047 curCopyTo = curRedirs;
2048 curLen = &curRedirsLen;
2049 lastWasRedirect = TRUE;
2052 /* See if 1>, 2> etc, in which case we have some patching up
2053 to do (provided there's a preceding whitespace, and enough
2054 chars read so far) */
2055 if (curStringLen > 2
2056 && (*(curPos-1)>='1') && (*(curPos-1)<='9')
2057 && ((*(curPos-2)==' ') || (*(curPos-2)=='\t'))) {
2058 curStringLen--;
2059 curString[curStringLen] = 0x00;
2060 curCopyTo[(*curLen)++] = *(curPos-1);
2063 curCopyTo[(*curLen)++] = *curPos;
2065 /* If a redirect is immediately followed by '&' (ie. 2>&1) then
2066 do not process that ampersand as an AND operator */
2067 if (thisChar == '>' && *(curPos+1) == '&') {
2068 curCopyTo[(*curLen)++] = *(curPos+1);
2069 curPos++;
2071 break;
2073 case '|': /* Pipe character only if not || */
2074 if (!inQuotes) {
2075 lastWasRedirect = FALSE;
2077 /* Add an entry to the command list */
2078 if (curStringLen > 0) {
2080 /* Add the current command */
2081 WCMD_addCommand(curString, &curStringLen,
2082 curRedirs, &curRedirsLen,
2083 &curCopyTo, &curLen,
2084 prevDelim, curDepth,
2085 &lastEntry, output);
2089 if (*(curPos+1) == '|') {
2090 curPos++; /* Skip other | */
2091 prevDelim = CMD_ONFAILURE;
2092 } else {
2093 prevDelim = CMD_PIPE;
2096 /* If in an IF or ELSE statement, put subsequent chained
2097 commands at a higher depth as if brackets were supplied
2098 but remember to reset to the original depth at EOL */
2099 if ((inIf || inElse) && curDepth == lineCurDepth) {
2100 curDepth++;
2101 resetAtEndOfLine = TRUE;
2103 } else {
2104 curCopyTo[(*curLen)++] = *curPos;
2106 break;
2108 case '"': if (WCMD_IsEndQuote(curPos, inQuotes)) {
2109 inQuotes--;
2110 } else {
2111 inQuotes++; /* Quotes within quotes are fun! */
2113 curCopyTo[(*curLen)++] = *curPos;
2114 lastWasRedirect = FALSE;
2115 break;
2117 case '(': /* If a '(' is the first non whitespace in a command portion
2118 ie start of line or just after &&, then we read until an
2119 unquoted ) is found */
2120 WINE_TRACE("Found '(' conditions: curLen(%d), inQ(%d), onlyWS(%d)"
2121 ", for(%d, In:%d, Do:%d)"
2122 ", if(%d, else:%d, lwe:%d)\n",
2123 *curLen, inQuotes,
2124 onlyWhiteSpace,
2125 inFor, lastWasIn, lastWasDo,
2126 inIf, inElse, lastWasElse);
2127 lastWasRedirect = FALSE;
2129 /* Ignore open brackets inside the for set */
2130 if (*curLen == 0 && !inIn) {
2131 curDepth++;
2133 /* If in quotes, ignore brackets */
2134 } else if (inQuotes) {
2135 curCopyTo[(*curLen)++] = *curPos;
2137 /* In a FOR loop, an unquoted '(' may occur straight after
2138 IN or DO
2139 In an IF statement just handle it regardless as we don't
2140 parse the operands
2141 In an ELSE statement, only allow it straight away after
2142 the ELSE and whitespace
2144 } else if ((inIf && !ignoreBracket) ||
2145 (inElse && lastWasElse && onlyWhiteSpace) ||
2146 (inFor && (lastWasIn || lastWasDo) && onlyWhiteSpace)) {
2148 /* If entering into an 'IN', set inIn */
2149 if (inFor && lastWasIn && onlyWhiteSpace) {
2150 WINE_TRACE("Inside an IN\n");
2151 inIn = TRUE;
2154 /* Add the current command */
2155 WCMD_addCommand(curString, &curStringLen,
2156 curRedirs, &curRedirsLen,
2157 &curCopyTo, &curLen,
2158 prevDelim, curDepth,
2159 &lastEntry, output);
2161 curDepth++;
2162 } else {
2163 curCopyTo[(*curLen)++] = *curPos;
2165 break;
2167 case '^': if (!inQuotes) {
2168 /* If we reach the end of the input, we need to wait for more */
2169 if (*(curPos+1) == 0x00) {
2170 lastWasCaret = TRUE;
2171 WINE_TRACE("Caret found at end of line\n");
2172 break;
2174 curPos++;
2176 curCopyTo[(*curLen)++] = *curPos;
2177 break;
2179 case '&': if (!inQuotes) {
2180 lastWasRedirect = FALSE;
2182 /* Add an entry to the command list */
2183 if (curStringLen > 0) {
2185 /* Add the current command */
2186 WCMD_addCommand(curString, &curStringLen,
2187 curRedirs, &curRedirsLen,
2188 &curCopyTo, &curLen,
2189 prevDelim, curDepth,
2190 &lastEntry, output);
2194 if (*(curPos+1) == '&') {
2195 curPos++; /* Skip other & */
2196 prevDelim = CMD_ONSUCCESS;
2197 } else {
2198 prevDelim = CMD_NONE;
2200 /* If in an IF or ELSE statement, put subsequent chained
2201 commands at a higher depth as if brackets were supplied
2202 but remember to reset to the original depth at EOL */
2203 if ((inIf || inElse) && curDepth == lineCurDepth) {
2204 curDepth++;
2205 resetAtEndOfLine = TRUE;
2207 } else {
2208 curCopyTo[(*curLen)++] = *curPos;
2210 break;
2212 case ')': if (!inQuotes && curDepth > 0) {
2213 lastWasRedirect = FALSE;
2215 /* Add the current command if there is one */
2216 if (curStringLen) {
2218 /* Add the current command */
2219 WCMD_addCommand(curString, &curStringLen,
2220 curRedirs, &curRedirsLen,
2221 &curCopyTo, &curLen,
2222 prevDelim, curDepth,
2223 &lastEntry, output);
2226 /* Add an empty entry to the command list */
2227 prevDelim = CMD_NONE;
2228 WCMD_addCommand(NULL, &curStringLen,
2229 curRedirs, &curRedirsLen,
2230 &curCopyTo, &curLen,
2231 prevDelim, curDepth,
2232 &lastEntry, output);
2233 curDepth--;
2235 /* Leave inIn if necessary */
2236 if (inIn) inIn = FALSE;
2237 } else {
2238 curCopyTo[(*curLen)++] = *curPos;
2240 break;
2241 default:
2242 lastWasRedirect = FALSE;
2243 curCopyTo[(*curLen)++] = *curPos;
2246 curPos++;
2248 /* At various times we need to know if we have only skipped whitespace,
2249 so reset this variable and then it will remain true until a non
2250 whitespace is found */
2251 if ((thisChar != ' ') && (thisChar != '\t') && (thisChar != '\n'))
2252 onlyWhiteSpace = FALSE;
2254 /* Flag end of interest in FOR DO and IN parms once something has been processed */
2255 if (!lastWasWhiteSpace) {
2256 lastWasIn = lastWasDo = FALSE;
2259 /* If we have reached the end, add this command into the list
2260 Do not add command to list if escape char ^ was last */
2261 if (*curPos == 0x00 && !lastWasCaret && *curLen > 0) {
2263 /* Add an entry to the command list */
2264 WCMD_addCommand(curString, &curStringLen,
2265 curRedirs, &curRedirsLen,
2266 &curCopyTo, &curLen,
2267 prevDelim, curDepth,
2268 &lastEntry, output);
2270 /* If we had a single line if or else, and we pretended to add
2271 brackets, end them now */
2272 if (resetAtEndOfLine) {
2273 WINE_TRACE("Resetting curdepth at end of line to %d\n", lineCurDepth);
2274 resetAtEndOfLine = FALSE;
2275 curDepth = lineCurDepth;
2279 /* If we have reached the end of the string, see if bracketing or
2280 final caret is outstanding */
2281 if (*curPos == 0x00 && (curDepth > 0 || lastWasCaret) &&
2282 readFrom != INVALID_HANDLE_VALUE) {
2283 WCHAR *extraData;
2285 WINE_TRACE("Need to read more data as outstanding brackets or carets\n");
2286 inOneLine = FALSE;
2287 prevDelim = CMD_NONE;
2288 inQuotes = 0;
2289 memset(extraSpace, 0x00, (MAXSTRING+1) * sizeof(WCHAR));
2290 extraData = extraSpace;
2292 /* Read more, skipping any blank lines */
2293 do {
2294 WINE_TRACE("Read more input\n");
2295 if (!context) WCMD_output_asis( WCMD_LoadMessage(WCMD_MOREPROMPT));
2296 if (!WCMD_fgets(extraData, MAXSTRING, readFrom))
2297 break;
2299 /* Edge case for carets - a completely blank line (i.e. was just
2300 CRLF) is oddly added as an LF but then more data is received (but
2301 only once more!) */
2302 if (lastWasCaret) {
2303 if (*extraSpace == 0x00) {
2304 WINE_TRACE("Read nothing, so appending LF char and will try again\n");
2305 *extraData++ = '\r';
2306 *extraData = 0x00;
2307 } else break;
2310 } while (*extraData == 0x00);
2311 curPos = extraSpace;
2313 /* Skip preceding whitespace */
2314 while (*curPos == ' ' || *curPos == '\t') curPos++;
2316 /* Replace env vars if in a batch context */
2317 if (context) handleExpansion(curPos, FALSE, FALSE);
2319 /* Continue to echo commands IF echo is on and in batch program */
2320 if (context && echo_mode && *curPos && *curPos != '@') {
2321 WCMD_output_asis(extraSpace);
2322 WCMD_output_asis(L"\r\n");
2325 /* Skip repeated 'no echo' characters and whitespace */
2326 while (*curPos == '@' || *curPos == ' ' || *curPos == '\t') curPos++;
2330 /* Dump out the parsed output */
2331 WCMD_DumpCommands(*output);
2333 return extraSpace;
2336 /***************************************************************************
2337 * WCMD_process_commands
2339 * Process all the commands read in so far
2341 CMD_LIST *WCMD_process_commands(CMD_LIST *thisCmd, BOOL oneBracket,
2342 BOOL retrycall) {
2344 int bdepth = -1;
2346 if (thisCmd && oneBracket) bdepth = thisCmd->bracketDepth;
2348 /* Loop through the commands, processing them one by one */
2349 while (thisCmd) {
2351 CMD_LIST *origCmd = thisCmd;
2353 /* If processing one bracket only, and we find the end bracket
2354 entry (or less), return */
2355 if (oneBracket && !thisCmd->command &&
2356 bdepth <= thisCmd->bracketDepth) {
2357 WINE_TRACE("Finished bracket @ %p, next command is %p\n",
2358 thisCmd, thisCmd->nextcommand);
2359 return thisCmd->nextcommand;
2362 /* Ignore the NULL entries a ')' inserts (Only 'if' cares
2363 about them and it will be handled in there)
2364 Also, skip over any batch labels (eg. :fred) */
2365 if (thisCmd->command && thisCmd->command[0] != ':') {
2366 WINE_TRACE("Executing command: '%s'\n", wine_dbgstr_w(thisCmd->command));
2367 WCMD_execute (thisCmd->command, thisCmd->redirects, &thisCmd, retrycall);
2370 /* Step on unless the command itself already stepped on */
2371 if (thisCmd == origCmd) thisCmd = thisCmd->nextcommand;
2373 return NULL;
2376 /***************************************************************************
2377 * WCMD_free_commands
2379 * Frees the storage held for a parsed command line
2380 * - This is not done in the process_commands, as eventually the current
2381 * pointer will be modified within the commands, and hence a single free
2382 * routine is simpler
2384 void WCMD_free_commands(CMD_LIST *cmds) {
2386 /* Loop through the commands, freeing them one by one */
2387 while (cmds) {
2388 CMD_LIST *thisCmd = cmds;
2389 cmds = cmds->nextcommand;
2390 heap_free(thisCmd->command);
2391 heap_free(thisCmd->redirects);
2392 heap_free(thisCmd);
2397 /*****************************************************************************
2398 * Main entry point. This is a console application so we have a main() not a
2399 * winmain().
2402 int __cdecl wmain (int argc, WCHAR *argvW[])
2404 WCHAR *cmdLine = NULL;
2405 WCHAR *cmd = NULL;
2406 WCHAR string[1024];
2407 WCHAR envvar[4];
2408 BOOL promptNewLine = TRUE;
2409 BOOL opt_q;
2410 int opt_t = 0;
2411 WCHAR comspec[MAX_PATH];
2412 CMD_LIST *toExecute = NULL; /* Commands left to be executed */
2413 RTL_OSVERSIONINFOEXW osv;
2414 char osver[50];
2415 STARTUPINFOW startupInfo;
2416 const WCHAR *arg;
2418 if (!GetEnvironmentVariableW(L"COMSPEC", comspec, ARRAY_SIZE(comspec)))
2420 GetSystemDirectoryW(comspec, ARRAY_SIZE(comspec) - ARRAY_SIZE(L"\\cmd.exe"));
2421 lstrcatW(comspec, L"\\cmd.exe");
2422 SetEnvironmentVariableW(L"COMSPEC", comspec);
2425 srand(time(NULL));
2427 /* Get the windows version being emulated */
2428 osv.dwOSVersionInfoSize = sizeof(osv);
2429 RtlGetVersion(&osv);
2431 /* Pre initialize some messages */
2432 lstrcpyW(anykey, WCMD_LoadMessage(WCMD_ANYKEY));
2433 sprintf(osver, "%d.%d.%d", osv.dwMajorVersion, osv.dwMinorVersion, osv.dwBuildNumber);
2434 cmd = WCMD_format_string(WCMD_LoadMessage(WCMD_VERSION), osver);
2435 lstrcpyW(version_string, cmd);
2436 LocalFree(cmd);
2437 cmd = NULL;
2439 /* Can't use argc/argv as it will have stripped quotes from parameters
2440 * meaning cmd.exe /C echo "quoted string" is impossible
2442 cmdLine = GetCommandLineW();
2443 WINE_TRACE("Full commandline '%s'\n", wine_dbgstr_w(cmdLine));
2445 while (*cmdLine && *cmdLine != '/') ++cmdLine;
2447 opt_c = opt_k = opt_q = opt_s = FALSE;
2449 for (arg = cmdLine; *arg; ++arg)
2451 if (arg[0] != '/')
2452 continue;
2454 switch (towlower(arg[1]))
2456 case 'a':
2457 unicodeOutput = FALSE;
2458 break;
2459 case 'c':
2460 opt_c = TRUE;
2461 break;
2462 case 'k':
2463 opt_k = TRUE;
2464 break;
2465 case 'q':
2466 opt_q = TRUE;
2467 break;
2468 case 's':
2469 opt_s = TRUE;
2470 break;
2471 case 't':
2472 if (arg[2] == ':')
2473 opt_t = wcstoul(&arg[3], NULL, 16);
2474 break;
2475 case 'u':
2476 unicodeOutput = TRUE;
2477 break;
2478 case 'v':
2479 if (arg[2] == ':')
2480 delayedsubst = wcsnicmp(&arg[3], L"OFF", 3);
2481 break;
2484 if (opt_c || opt_k)
2486 arg += 2;
2487 break;
2491 while (*arg && wcschr(L" \t,=;", *arg)) arg++;
2493 if (opt_q) {
2494 WCMD_echo(L"OFF");
2497 /* Until we start to read from the keyboard, stay as non-interactive */
2498 interactive = FALSE;
2500 SetEnvironmentVariableW(L"PROMPT", L"$P$G");
2502 if (opt_c || opt_k) {
2503 int len;
2504 WCHAR *q1 = NULL,*q2 = NULL,*p;
2506 /* Take a copy */
2507 cmd = heap_strdupW(arg);
2509 /* opt_s left unflagged if the command starts with and contains exactly
2510 * one quoted string (exactly two quote characters). The quoted string
2511 * must be an executable name that has whitespace and must not have the
2512 * following characters: &<>()@^| */
2514 if (!opt_s) {
2515 /* 1. Confirm there is at least one quote */
2516 q1 = wcschr(arg, '"');
2517 if (!q1) opt_s=1;
2520 if (!opt_s) {
2521 /* 2. Confirm there is a second quote */
2522 q2 = wcschr(q1+1, '"');
2523 if (!q2) opt_s=1;
2526 if (!opt_s) {
2527 /* 3. Ensure there are no more quotes */
2528 if (wcschr(q2+1, '"')) opt_s=1;
2531 /* check first parameter for a space and invalid characters. There must not be any
2532 * invalid characters, but there must be one or more whitespace */
2533 if (!opt_s) {
2534 opt_s = TRUE;
2535 p=q1;
2536 while (p!=q2) {
2537 if (*p=='&' || *p=='<' || *p=='>' || *p=='(' || *p==')'
2538 || *p=='@' || *p=='^' || *p=='|') {
2539 opt_s = TRUE;
2540 break;
2542 if (*p==' ' || *p=='\t')
2543 opt_s = FALSE;
2544 p++;
2548 WINE_TRACE("/c command line: '%s'\n", wine_dbgstr_w(cmd));
2550 /* Finally, we only stay in new mode IF the first parameter is quoted and
2551 is a valid executable, i.e. must exist, otherwise drop back to old mode */
2552 if (!opt_s) {
2553 WCHAR *thisArg = WCMD_parameter(cmd, 0, NULL, FALSE, TRUE);
2554 WCHAR pathext[MAXSTRING];
2555 BOOL found = FALSE;
2557 /* Now extract PATHEXT */
2558 len = GetEnvironmentVariableW(L"PATHEXT", pathext, ARRAY_SIZE(pathext));
2559 if ((len == 0) || (len >= ARRAY_SIZE(pathext))) {
2560 lstrcpyW(pathext, L".bat;.com;.cmd;.exe");
2563 /* If the supplied parameter has any directory information, look there */
2564 WINE_TRACE("First parameter is '%s'\n", wine_dbgstr_w(thisArg));
2565 if (wcschr(thisArg, '\\') != NULL) {
2567 GetFullPathNameW(thisArg, ARRAY_SIZE(string), string, NULL);
2568 WINE_TRACE("Full path name '%s'\n", wine_dbgstr_w(string));
2569 p = string + lstrlenW(string);
2571 /* Does file exist with this name? */
2572 if (GetFileAttributesW(string) != INVALID_FILE_ATTRIBUTES) {
2573 WINE_TRACE("Found file as '%s'\n", wine_dbgstr_w(string));
2574 found = TRUE;
2575 } else {
2576 WCHAR *thisExt = pathext;
2578 /* No - try with each of the PATHEXT extensions */
2579 while (!found && thisExt) {
2580 WCHAR *nextExt = wcschr(thisExt, ';');
2582 if (nextExt) {
2583 memcpy(p, thisExt, (nextExt-thisExt) * sizeof(WCHAR));
2584 p[(nextExt-thisExt)] = 0x00;
2585 thisExt = nextExt+1;
2586 } else {
2587 lstrcpyW(p, thisExt);
2588 thisExt = NULL;
2591 /* Does file exist with this extension appended? */
2592 if (GetFileAttributesW(string) != INVALID_FILE_ATTRIBUTES) {
2593 WINE_TRACE("Found file as '%s'\n", wine_dbgstr_w(string));
2594 found = TRUE;
2599 /* Otherwise we now need to look in the path to see if we can find it */
2600 } else {
2601 /* Does file exist with this name? */
2602 if (SearchPathW(NULL, thisArg, NULL, ARRAY_SIZE(string), string, NULL) != 0) {
2603 WINE_TRACE("Found on path as '%s'\n", wine_dbgstr_w(string));
2604 found = TRUE;
2605 } else {
2606 WCHAR *thisExt = pathext;
2608 /* No - try with each of the PATHEXT extensions */
2609 while (!found && thisExt) {
2610 WCHAR *nextExt = wcschr(thisExt, ';');
2612 if (nextExt) {
2613 *nextExt = 0;
2614 nextExt = nextExt+1;
2615 } else {
2616 nextExt = NULL;
2619 /* Does file exist with this extension? */
2620 if (SearchPathW(NULL, thisArg, thisExt, ARRAY_SIZE(string), string, NULL) != 0) {
2621 WINE_TRACE("Found on path as '%s' with extension '%s'\n", wine_dbgstr_w(string),
2622 wine_dbgstr_w(thisExt));
2623 found = TRUE;
2625 thisExt = nextExt;
2630 /* If not found, drop back to old behaviour */
2631 if (!found) {
2632 WINE_TRACE("Binary not found, dropping back to old behaviour\n");
2633 opt_s = TRUE;
2638 /* strip first and last quote characters if opt_s; check for invalid
2639 * executable is done later */
2640 if (opt_s && *cmd=='\"')
2641 WCMD_strip_quotes(cmd);
2644 /* Save cwd into appropriate env var (Must be before the /c processing */
2645 GetCurrentDirectoryW(ARRAY_SIZE(string), string);
2646 if (IsCharAlphaW(string[0]) && string[1] == ':') {
2647 wsprintfW(envvar, L"=%c:", string[0]);
2648 SetEnvironmentVariableW(envvar, string);
2649 WINE_TRACE("Set %s to %s\n", wine_dbgstr_w(envvar), wine_dbgstr_w(string));
2652 if (opt_c) {
2653 /* If we do a "cmd /c command", we don't want to allocate a new
2654 * console since the command returns immediately. Rather, we use
2655 * the currently allocated input and output handles. This allows
2656 * us to pipe to and read from the command interpreter.
2659 /* Parse the command string, without reading any more input */
2660 WCMD_ReadAndParseLine(cmd, &toExecute, INVALID_HANDLE_VALUE);
2661 WCMD_process_commands(toExecute, FALSE, FALSE);
2662 WCMD_free_commands(toExecute);
2663 toExecute = NULL;
2665 heap_free(cmd);
2666 return errorlevel;
2669 GetStartupInfoW(&startupInfo);
2670 if (startupInfo.lpTitle != NULL)
2671 SetConsoleTitleW(startupInfo.lpTitle);
2672 else
2673 SetConsoleTitleW(WCMD_LoadMessage(WCMD_CONSTITLE));
2675 /* Note: cmd.exe /c dir does not get a new color, /k dir does */
2676 if (opt_t) {
2677 if (!(((opt_t & 0xF0) >> 4) == (opt_t & 0x0F))) {
2678 defaultColor = opt_t & 0xFF;
2679 param1[0] = 0x00;
2680 WCMD_color();
2682 } else {
2683 /* Check HKCU\Software\Microsoft\Command Processor
2684 Then HKLM\Software\Microsoft\Command Processor
2685 for defaultcolour value
2686 Note Can be supplied as DWORD or REG_SZ
2687 Note2 When supplied as REG_SZ it's in decimal!!! */
2688 HKEY key;
2689 DWORD type;
2690 DWORD value=0, size=4;
2691 static const WCHAR regKeyW[] = L"Software\\Microsoft\\Command Processor";
2693 if (RegOpenKeyExW(HKEY_CURRENT_USER, regKeyW,
2694 0, KEY_READ, &key) == ERROR_SUCCESS) {
2695 WCHAR strvalue[4];
2697 /* See if DWORD or REG_SZ */
2698 if (RegQueryValueExW(key, L"DefaultColor", NULL, &type, NULL, NULL) == ERROR_SUCCESS) {
2699 if (type == REG_DWORD) {
2700 size = sizeof(DWORD);
2701 RegQueryValueExW(key, L"DefaultColor", NULL, NULL, (BYTE *)&value, &size);
2702 } else if (type == REG_SZ) {
2703 size = ARRAY_SIZE(strvalue);
2704 RegQueryValueExW(key, L"DefaultColor", NULL, NULL, (BYTE *)strvalue, &size);
2705 value = wcstoul(strvalue, NULL, 10);
2708 RegCloseKey(key);
2711 if (value == 0 && RegOpenKeyExW(HKEY_LOCAL_MACHINE, regKeyW,
2712 0, KEY_READ, &key) == ERROR_SUCCESS) {
2713 WCHAR strvalue[4];
2715 /* See if DWORD or REG_SZ */
2716 if (RegQueryValueExW(key, L"DefaultColor", NULL, &type,
2717 NULL, NULL) == ERROR_SUCCESS) {
2718 if (type == REG_DWORD) {
2719 size = sizeof(DWORD);
2720 RegQueryValueExW(key, L"DefaultColor", NULL, NULL, (BYTE *)&value, &size);
2721 } else if (type == REG_SZ) {
2722 size = ARRAY_SIZE(strvalue);
2723 RegQueryValueExW(key, L"DefaultColor", NULL, NULL, (BYTE *)strvalue, &size);
2724 value = wcstoul(strvalue, NULL, 10);
2727 RegCloseKey(key);
2730 /* If one found, set the screen to that colour */
2731 if (!(((value & 0xF0) >> 4) == (value & 0x0F))) {
2732 defaultColor = value & 0xFF;
2733 param1[0] = 0x00;
2734 WCMD_color();
2739 if (opt_k) {
2740 /* Parse the command string, without reading any more input */
2741 WCMD_ReadAndParseLine(cmd, &toExecute, INVALID_HANDLE_VALUE);
2742 WCMD_process_commands(toExecute, FALSE, FALSE);
2743 WCMD_free_commands(toExecute);
2744 toExecute = NULL;
2745 heap_free(cmd);
2749 * Loop forever getting commands and executing them.
2752 interactive = TRUE;
2753 if (!opt_k) WCMD_version ();
2754 while (TRUE) {
2756 /* Read until EOF (which for std input is never, but if redirect
2757 in place, may occur */
2758 if (echo_mode) WCMD_show_prompt(promptNewLine);
2759 if (!WCMD_ReadAndParseLine(NULL, &toExecute, GetStdHandle(STD_INPUT_HANDLE)))
2760 break;
2761 WCMD_process_commands(toExecute, FALSE, FALSE);
2762 WCMD_free_commands(toExecute);
2763 promptNewLine = !!toExecute;
2764 toExecute = NULL;
2766 return 0;