cmd: Merge two if blocks.
[wine/multimedia.git] / programs / cmd / wcmdmain.c
blob67a524d73ae7cfa8c32801b7402b8917cb25e9ef
1 /*
2 * CMD - Wine-compatible command line interface.
4 * Copyright (C) 1999 - 2001 D A Pickles
5 * Copyright (C) 2007 J Edmeades
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23 * FIXME:
24 * - Cannot handle parameters in quotes
25 * - Lots of functionality missing from builtins
28 #include "config.h"
29 #include "wcmd.h"
30 #include "wine/debug.h"
32 WINE_DEFAULT_DEBUG_CHANNEL(cmd);
34 extern const WCHAR inbuilt[][10];
35 extern struct env_stack *pushd_directories;
37 BATCH_CONTEXT *context = NULL;
38 DWORD errorlevel;
39 WCHAR quals[MAX_PATH], param1[MAXSTRING], param2[MAXSTRING];
41 int defaultColor = 7;
42 BOOL echo_mode = TRUE;
44 WCHAR anykey[100], version_string[100];
45 const WCHAR newline[] = {'\r','\n','\0'};
46 const WCHAR space[] = {' ','\0'};
48 static BOOL opt_c, opt_k, opt_s, unicodeOutput = FALSE;
50 /* Variables pertaining to paging */
51 static BOOL paged_mode;
52 static const WCHAR *pagedMessage = NULL;
53 static int line_count;
54 static int max_height;
55 static int max_width;
56 static int numChars;
58 #define MAX_WRITECONSOLE_SIZE 65535
61 * Returns a buffer for reading from/writing to file
62 * Never freed
64 static char *get_file_buffer(void)
66 static char *output_bufA = NULL;
67 if (!output_bufA) {
68 output_bufA = HeapAlloc(GetProcessHeap(), 0, MAX_WRITECONSOLE_SIZE);
69 if (!output_bufA)
70 WINE_FIXME("Out of memory - could not allocate ansi 64K buffer\n");
72 return output_bufA;
75 /*******************************************************************
76 * WCMD_output_asis_len - send output to current standard output
78 * Output a formatted unicode string. Ideally this will go to the console
79 * and hence required WriteConsoleW to output it, however if file i/o is
80 * redirected, it needs to be WriteFile'd using OEM (not ANSI) format
82 static void WCMD_output_asis_len(const WCHAR *message, DWORD len, HANDLE device)
84 DWORD nOut= 0;
85 DWORD res = 0;
87 /* If nothing to write, return (MORE does this sometimes) */
88 if (!len) return;
90 /* Try to write as unicode assuming it is to a console */
91 res = WriteConsoleW(device, message, len, &nOut, NULL);
93 /* If writing to console fails, assume its file
94 i/o so convert to OEM codepage and output */
95 if (!res) {
96 BOOL usedDefaultChar = FALSE;
97 DWORD convertedChars;
98 char *buffer;
100 if (!unicodeOutput) {
102 if (!(buffer = get_file_buffer()))
103 return;
105 /* Convert to OEM, then output */
106 convertedChars = WideCharToMultiByte(GetConsoleOutputCP(), 0, message,
107 len, buffer, MAX_WRITECONSOLE_SIZE,
108 "?", &usedDefaultChar);
109 WriteFile(device, buffer, convertedChars,
110 &nOut, FALSE);
111 } else {
112 WriteFile(device, message, len*sizeof(WCHAR),
113 &nOut, FALSE);
116 return;
119 /*******************************************************************
120 * WCMD_output - send output to current standard output device.
124 void CDECL WCMD_output (const WCHAR *format, ...) {
126 __ms_va_list ap;
127 WCHAR* string;
128 DWORD len;
130 __ms_va_start(ap,format);
131 SetLastError(NO_ERROR);
132 string = NULL;
133 len = FormatMessageW(FORMAT_MESSAGE_FROM_STRING|FORMAT_MESSAGE_ALLOCATE_BUFFER,
134 format, 0, 0, (LPWSTR)&string, 0, &ap);
135 __ms_va_end(ap);
136 if (len == 0 && GetLastError() != NO_ERROR)
137 WINE_FIXME("Could not format string: le=%u, fmt=%s\n", GetLastError(), wine_dbgstr_w(format));
138 else
140 WCMD_output_asis_len(string, len, GetStdHandle(STD_OUTPUT_HANDLE));
141 LocalFree(string);
145 /*******************************************************************
146 * WCMD_output_stderr - send output to current standard error device.
150 void CDECL WCMD_output_stderr (const WCHAR *format, ...) {
152 __ms_va_list ap;
153 WCHAR* string;
154 DWORD len;
156 __ms_va_start(ap,format);
157 SetLastError(NO_ERROR);
158 string = NULL;
159 len = FormatMessageW(FORMAT_MESSAGE_FROM_STRING|FORMAT_MESSAGE_ALLOCATE_BUFFER,
160 format, 0, 0, (LPWSTR)&string, 0, &ap);
161 __ms_va_end(ap);
162 if (len == 0 && GetLastError() != NO_ERROR)
163 WINE_FIXME("Could not format string: le=%u, fmt=%s\n", GetLastError(), wine_dbgstr_w(format));
164 else
166 WCMD_output_asis_len(string, len, GetStdHandle(STD_ERROR_HANDLE));
167 LocalFree(string);
171 /*******************************************************************
172 * WCMD_format_string - allocate a buffer and format a string
176 WCHAR* CDECL WCMD_format_string (const WCHAR *format, ...) {
178 __ms_va_list ap;
179 WCHAR* string;
180 DWORD len;
182 __ms_va_start(ap,format);
183 SetLastError(NO_ERROR);
184 len = FormatMessageW(FORMAT_MESSAGE_FROM_STRING|FORMAT_MESSAGE_ALLOCATE_BUFFER,
185 format, 0, 0, (LPWSTR)&string, 0, &ap);
186 __ms_va_end(ap);
187 if (len == 0 && GetLastError() != NO_ERROR) {
188 WINE_FIXME("Could not format string: le=%u, fmt=%s\n", GetLastError(), wine_dbgstr_w(format));
189 string = (WCHAR*)LocalAlloc(LMEM_FIXED, 2);
190 *string = 0;
192 return string;
195 void WCMD_enter_paged_mode(const WCHAR *msg)
197 CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
199 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &consoleInfo)) {
200 max_height = consoleInfo.dwSize.Y;
201 max_width = consoleInfo.dwSize.X;
202 } else {
203 max_height = 25;
204 max_width = 80;
206 paged_mode = TRUE;
207 line_count = 0;
208 numChars = 0;
209 pagedMessage = (msg==NULL)? anykey : msg;
212 void WCMD_leave_paged_mode(void)
214 paged_mode = FALSE;
215 pagedMessage = NULL;
218 /***************************************************************************
219 * WCMD_Readfile
221 * Read characters in from a console/file, returning result in Unicode
223 BOOL WCMD_ReadFile(const HANDLE hIn, WCHAR *intoBuf, const DWORD maxChars, LPDWORD charsRead)
225 DWORD numRead;
226 char *buffer;
228 if (WCMD_is_console_handle(hIn))
229 /* Try to read from console as Unicode */
230 return ReadConsoleW(hIn, intoBuf, maxChars, charsRead, NULL);
232 /* We assume it's a file handle and read then convert from assumed OEM codepage */
233 if (!(buffer = get_file_buffer()))
234 return FALSE;
236 if (!ReadFile(hIn, buffer, maxChars, &numRead, NULL))
237 return FALSE;
239 *charsRead = MultiByteToWideChar(GetConsoleCP(), 0, buffer, numRead, intoBuf, maxChars);
241 return TRUE;
244 /*******************************************************************
245 * WCMD_output_asis_handle
247 * Send output to specified handle without formatting e.g. when message contains '%'
249 static void WCMD_output_asis_handle (DWORD std_handle, const WCHAR *message) {
250 DWORD count;
251 const WCHAR* ptr;
252 WCHAR string[1024];
253 HANDLE handle = GetStdHandle(std_handle);
255 if (paged_mode) {
256 do {
257 ptr = message;
258 while (*ptr && *ptr!='\n' && (numChars < max_width)) {
259 numChars++;
260 ptr++;
262 if (*ptr == '\n') ptr++;
263 WCMD_output_asis_len(message, ptr - message, handle);
264 numChars = 0;
265 if (++line_count >= max_height - 1) {
266 line_count = 0;
267 WCMD_output_asis_len(pagedMessage, strlenW(pagedMessage), handle);
268 WCMD_ReadFile(GetStdHandle(STD_INPUT_HANDLE), string, sizeof(string)/sizeof(WCHAR), &count);
270 } while (((message = ptr) != NULL) && (*ptr));
271 } else {
272 WCMD_output_asis_len(message, lstrlenW(message), handle);
276 /*******************************************************************
277 * WCMD_output_asis
279 * Send output to current standard output device, without formatting
280 * e.g. when message contains '%'
282 void WCMD_output_asis (const WCHAR *message) {
283 WCMD_output_asis_handle(STD_OUTPUT_HANDLE, message);
286 /*******************************************************************
287 * WCMD_output_asis_stderr
289 * Send output to current standard error device, without formatting
290 * e.g. when message contains '%'
292 void WCMD_output_asis_stderr (const WCHAR *message) {
293 WCMD_output_asis_handle(STD_ERROR_HANDLE, message);
296 /****************************************************************************
297 * WCMD_print_error
299 * Print the message for GetLastError
302 void WCMD_print_error (void) {
303 LPVOID lpMsgBuf;
304 DWORD error_code;
305 int status;
307 error_code = GetLastError ();
308 status = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
309 NULL, error_code, 0, (LPWSTR) &lpMsgBuf, 0, NULL);
310 if (!status) {
311 WINE_FIXME ("Cannot display message for error %d, status %d\n",
312 error_code, GetLastError());
313 return;
316 WCMD_output_asis_len(lpMsgBuf, lstrlenW(lpMsgBuf),
317 GetStdHandle(STD_ERROR_HANDLE));
318 LocalFree (lpMsgBuf);
319 WCMD_output_asis_len (newline, lstrlenW(newline),
320 GetStdHandle(STD_ERROR_HANDLE));
321 return;
324 /******************************************************************************
325 * WCMD_show_prompt
327 * Display the prompt on STDout
331 static void WCMD_show_prompt (void) {
333 int status;
334 WCHAR out_string[MAX_PATH], curdir[MAX_PATH], prompt_string[MAX_PATH];
335 WCHAR *p, *q;
336 DWORD len;
337 static const WCHAR envPrompt[] = {'P','R','O','M','P','T','\0'};
339 len = GetEnvironmentVariableW(envPrompt, prompt_string,
340 sizeof(prompt_string)/sizeof(WCHAR));
341 if ((len == 0) || (len >= (sizeof(prompt_string)/sizeof(WCHAR)))) {
342 static const WCHAR dfltPrompt[] = {'$','P','$','G','\0'};
343 strcpyW (prompt_string, dfltPrompt);
345 p = prompt_string;
346 q = out_string;
347 *q++ = '\r';
348 *q++ = '\n';
349 *q = '\0';
350 while (*p != '\0') {
351 if (*p != '$') {
352 *q++ = *p++;
353 *q = '\0';
355 else {
356 p++;
357 switch (toupper(*p)) {
358 case '$':
359 *q++ = '$';
360 break;
361 case 'A':
362 *q++ = '&';
363 break;
364 case 'B':
365 *q++ = '|';
366 break;
367 case 'C':
368 *q++ = '(';
369 break;
370 case 'D':
371 GetDateFormatW(LOCALE_USER_DEFAULT, DATE_SHORTDATE, NULL, NULL, q, MAX_PATH);
372 while (*q) q++;
373 break;
374 case 'E':
375 *q++ = '\E';
376 break;
377 case 'F':
378 *q++ = ')';
379 break;
380 case 'G':
381 *q++ = '>';
382 break;
383 case 'H':
384 *q++ = '\b';
385 break;
386 case 'L':
387 *q++ = '<';
388 break;
389 case 'N':
390 status = GetCurrentDirectoryW(sizeof(curdir)/sizeof(WCHAR), curdir);
391 if (status) {
392 *q++ = curdir[0];
394 break;
395 case 'P':
396 status = GetCurrentDirectoryW(sizeof(curdir)/sizeof(WCHAR), curdir);
397 if (status) {
398 strcatW (q, curdir);
399 while (*q) q++;
401 break;
402 case 'Q':
403 *q++ = '=';
404 break;
405 case 'S':
406 *q++ = ' ';
407 break;
408 case 'T':
409 GetTimeFormatW(LOCALE_USER_DEFAULT, 0, NULL, NULL, q, MAX_PATH);
410 while (*q) q++;
411 break;
412 case 'V':
413 strcatW (q, version_string);
414 while (*q) q++;
415 break;
416 case '_':
417 *q++ = '\n';
418 break;
419 case '+':
420 if (pushd_directories) {
421 memset(q, '+', pushd_directories->u.stackdepth);
422 q = q + pushd_directories->u.stackdepth;
424 break;
426 p++;
427 *q = '\0';
430 WCMD_output_asis (out_string);
434 /*************************************************************************
435 * WCMD_strdupW
436 * A wide version of strdup as its missing from unicode.h
438 WCHAR *WCMD_strdupW(const WCHAR *input) {
439 int len=strlenW(input)+1;
440 WCHAR *result = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
441 memcpy(result, input, len * sizeof(WCHAR));
442 return result;
445 /*************************************************************************
446 * WCMD_strsubstW
447 * Replaces a portion of a Unicode string with the specified string.
448 * It's up to the caller to ensure there is enough space in the
449 * destination buffer.
451 void WCMD_strsubstW(WCHAR *start, const WCHAR *next, const WCHAR *insert, int len) {
453 if (len < 0)
454 len=insert ? lstrlenW(insert) : 0;
455 if (start+len != next)
456 memmove(start+len, next, (strlenW(next) + 1) * sizeof(*next));
457 if (insert)
458 memcpy(start, insert, len * sizeof(*insert));
461 /***************************************************************************
462 * WCMD_skip_leading_spaces
464 * Return a pointer to the first non-whitespace character of string.
465 * Does not modify the input string.
467 WCHAR *WCMD_skip_leading_spaces (WCHAR *string) {
469 WCHAR *ptr;
471 ptr = string;
472 while (*ptr == ' ' || *ptr == '\t') ptr++;
473 return ptr;
476 /***************************************************************************
477 * WCMD_keyword_ws_found
479 * Checks if the string located at ptr matches a keyword (of length len)
480 * followed by a whitespace character (space or tab)
482 BOOL WCMD_keyword_ws_found(const WCHAR *keyword, int len, const WCHAR *ptr) {
483 return (CompareStringW(LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
484 ptr, len, keyword, len) == CSTR_EQUAL)
485 && ((*(ptr + len) == ' ') || (*(ptr + len) == '\t'));
488 /*************************************************************************
489 * WCMD_strip_quotes
491 * Remove first and last quote WCHARacters, preserving all other text
493 void WCMD_strip_quotes(WCHAR *cmd) {
494 WCHAR *src = cmd + 1, *dest = cmd, *lastq = NULL;
495 while((*dest=*src) != '\0') {
496 if (*src=='\"')
497 lastq=dest;
498 dest++, src++;
500 if (lastq) {
501 dest=lastq++;
502 while ((*dest++=*lastq++) != 0)
508 /*************************************************************************
509 * WCMD_is_magic_envvar
510 * Return TRUE if s is '%'magicvar'%'
511 * and is not masked by a real environment variable.
514 static inline BOOL WCMD_is_magic_envvar(const WCHAR *s, const WCHAR *magicvar)
516 int len;
518 if (s[0] != '%')
519 return FALSE; /* Didn't begin with % */
520 len = strlenW(s);
521 if (len < 2 || s[len-1] != '%')
522 return FALSE; /* Didn't end with another % */
524 if (CompareStringW(LOCALE_USER_DEFAULT,
525 NORM_IGNORECASE | SORT_STRINGSORT,
526 s+1, len-2, magicvar, -1) != CSTR_EQUAL) {
527 /* Name doesn't match. */
528 return FALSE;
531 if (GetEnvironmentVariableW(magicvar, NULL, 0) > 0) {
532 /* Masked by real environment variable. */
533 return FALSE;
536 return TRUE;
539 /*************************************************************************
540 * WCMD_expand_envvar
542 * Expands environment variables, allowing for WCHARacter substitution
544 static WCHAR *WCMD_expand_envvar(WCHAR *start,
545 const WCHAR *forVar, const WCHAR *forVal) {
546 WCHAR *endOfVar = NULL, *s;
547 WCHAR *colonpos = NULL;
548 WCHAR thisVar[MAXSTRING];
549 WCHAR thisVarContents[MAXSTRING];
550 WCHAR savedchar = 0x00;
551 int len;
553 static const WCHAR ErrorLvl[] = {'E','R','R','O','R','L','E','V','E','L','\0'};
554 static const WCHAR Date[] = {'D','A','T','E','\0'};
555 static const WCHAR Time[] = {'T','I','M','E','\0'};
556 static const WCHAR Cd[] = {'C','D','\0'};
557 static const WCHAR Random[] = {'R','A','N','D','O','M','\0'};
558 static const WCHAR Delims[] = {'%',' ',':','\0'};
560 WINE_TRACE("Expanding: %s (%s,%s)\n", wine_dbgstr_w(start),
561 wine_dbgstr_w(forVal), wine_dbgstr_w(forVar));
563 /* Find the end of the environment variable, and extract name */
564 endOfVar = strpbrkW(start+1, Delims);
566 if (endOfVar == NULL || *endOfVar==' ') {
568 /* In batch program, missing terminator for % and no following
569 ':' just removes the '%' */
570 if (context) {
571 WCMD_strsubstW(start, start + 1, NULL, 0);
572 return start;
573 } else {
575 /* In command processing, just ignore it - allows command line
576 syntax like: for %i in (a.a) do echo %i */
577 return start+1;
581 /* If ':' found, process remaining up until '%' (or stop at ':' if
582 a missing '%' */
583 if (*endOfVar==':') {
584 WCHAR *endOfVar2 = strchrW(endOfVar+1, '%');
585 if (endOfVar2 != NULL) endOfVar = endOfVar2;
588 memcpy(thisVar, start, ((endOfVar - start) + 1) * sizeof(WCHAR));
589 thisVar[(endOfVar - start)+1] = 0x00;
590 colonpos = strchrW(thisVar+1, ':');
592 /* If there's complex substitution, just need %var% for now
593 to get the expanded data to play with */
594 if (colonpos) {
595 *colonpos = '%';
596 savedchar = *(colonpos+1);
597 *(colonpos+1) = 0x00;
600 WINE_TRACE("Retrieving contents of %s\n", wine_dbgstr_w(thisVar));
602 /* Expand to contents, if unchanged, return */
603 /* Handle DATE, TIME, ERRORLEVEL and CD replacements allowing */
604 /* override if existing env var called that name */
605 if (WCMD_is_magic_envvar(thisVar, ErrorLvl)) {
606 static const WCHAR fmt[] = {'%','d','\0'};
607 wsprintfW(thisVarContents, fmt, errorlevel);
608 len = strlenW(thisVarContents);
609 } else if (WCMD_is_magic_envvar(thisVar, Date)) {
610 GetDateFormatW(LOCALE_USER_DEFAULT, DATE_SHORTDATE, NULL,
611 NULL, thisVarContents, MAXSTRING);
612 len = strlenW(thisVarContents);
613 } else if (WCMD_is_magic_envvar(thisVar, Time)) {
614 GetTimeFormatW(LOCALE_USER_DEFAULT, TIME_NOSECONDS, NULL,
615 NULL, thisVarContents, MAXSTRING);
616 len = strlenW(thisVarContents);
617 } else if (WCMD_is_magic_envvar(thisVar, Cd)) {
618 GetCurrentDirectoryW(MAXSTRING, thisVarContents);
619 len = strlenW(thisVarContents);
620 } else if (WCMD_is_magic_envvar(thisVar, Random)) {
621 static const WCHAR fmt[] = {'%','d','\0'};
622 wsprintfW(thisVarContents, fmt, rand() % 32768);
623 len = strlenW(thisVarContents);
625 /* Look for a matching 'for' variable */
626 } else if (forVar &&
627 (CompareStringW(LOCALE_USER_DEFAULT,
628 SORT_STRINGSORT,
629 thisVar,
630 (colonpos - thisVar) - 1,
631 forVar, -1) == CSTR_EQUAL)) {
632 strcpyW(thisVarContents, forVal);
633 len = strlenW(thisVarContents);
635 } else {
637 len = ExpandEnvironmentStringsW(thisVar, thisVarContents,
638 sizeof(thisVarContents)/sizeof(WCHAR));
641 if (len == 0)
642 return endOfVar+1;
644 /* In a batch program, unknown env vars are replaced with nothing,
645 note syntax %garbage:1,3% results in anything after the ':'
646 except the %
647 From the command line, you just get back what you entered */
648 if (lstrcmpiW(thisVar, thisVarContents) == 0) {
650 /* Restore the complex part after the compare */
651 if (colonpos) {
652 *colonpos = ':';
653 *(colonpos+1) = savedchar;
656 /* Command line - just ignore this */
657 if (context == NULL) return endOfVar+1;
660 /* Batch - replace unknown env var with nothing */
661 if (colonpos == NULL) {
662 WCMD_strsubstW(start, endOfVar + 1, NULL, 0);
663 } else {
664 len = strlenW(thisVar);
665 thisVar[len-1] = 0x00;
666 /* If %:...% supplied, : is retained */
667 if (colonpos == thisVar+1) {
668 WCMD_strsubstW(start, endOfVar + 1, colonpos, -1);
669 } else {
670 WCMD_strsubstW(start, endOfVar + 1, colonpos + 1, -1);
673 return start;
677 /* See if we need to do complex substitution (any ':'s), if not
678 then our work here is done */
679 if (colonpos == NULL) {
680 WCMD_strsubstW(start, endOfVar + 1, thisVarContents, -1);
681 return start;
684 /* Restore complex bit */
685 *colonpos = ':';
686 *(colonpos+1) = savedchar;
689 Handle complex substitutions:
690 xxx=yyy (replace xxx with yyy)
691 *xxx=yyy (replace up to and including xxx with yyy)
692 ~x (from x WCHARs in)
693 ~-x (from x WCHARs from the end)
694 ~x,y (from x WCHARs in for y WCHARacters)
695 ~x,-y (from x WCHARs in until y WCHARacters from the end)
698 /* ~ is substring manipulation */
699 if (savedchar == '~') {
701 int substrposition, substrlength = 0;
702 WCHAR *commapos = strchrW(colonpos+2, ',');
703 WCHAR *startCopy;
705 substrposition = atolW(colonpos+2);
706 if (commapos) substrlength = atolW(commapos+1);
708 /* Check bounds */
709 if (substrposition >= 0) {
710 startCopy = &thisVarContents[min(substrposition, len)];
711 } else {
712 startCopy = &thisVarContents[max(0, len+substrposition-1)];
715 if (commapos == NULL) {
716 /* Copy the lot */
717 WCMD_strsubstW(start, endOfVar + 1, startCopy, -1);
718 } else if (substrlength < 0) {
720 int copybytes = (len+substrlength-1)-(startCopy-thisVarContents);
721 if (copybytes > len) copybytes = len;
722 else if (copybytes < 0) copybytes = 0;
723 WCMD_strsubstW(start, endOfVar + 1, startCopy, copybytes);
724 } else {
725 WCMD_strsubstW(start, endOfVar + 1, startCopy, substrlength);
728 return start;
730 /* search and replace manipulation */
731 } else {
732 WCHAR *equalspos = strstrW(colonpos, equalW);
733 WCHAR *replacewith = equalspos+1;
734 WCHAR *found = NULL;
735 WCHAR *searchIn;
736 WCHAR *searchFor;
738 if (equalspos == NULL) return start+1;
739 s = WCMD_strdupW(endOfVar + 1);
741 /* Null terminate both strings */
742 thisVar[strlenW(thisVar)-1] = 0x00;
743 *equalspos = 0x00;
745 /* Since we need to be case insensitive, copy the 2 buffers */
746 searchIn = WCMD_strdupW(thisVarContents);
747 CharUpperBuffW(searchIn, strlenW(thisVarContents));
748 searchFor = WCMD_strdupW(colonpos+1);
749 CharUpperBuffW(searchFor, strlenW(colonpos+1));
751 /* Handle wildcard case */
752 if (*(colonpos+1) == '*') {
753 /* Search for string to replace */
754 found = strstrW(searchIn, searchFor+1);
756 if (found) {
757 /* Do replacement */
758 strcpyW(start, replacewith);
759 strcatW(start, thisVarContents + (found-searchIn) + strlenW(searchFor+1));
760 strcatW(start, s);
761 } else {
762 /* Copy as is */
763 strcpyW(start, thisVarContents);
764 strcatW(start, s);
767 } else {
768 /* Loop replacing all instances */
769 WCHAR *lastFound = searchIn;
770 WCHAR *outputposn = start;
772 *start = 0x00;
773 while ((found = strstrW(lastFound, searchFor))) {
774 lstrcpynW(outputposn,
775 thisVarContents + (lastFound-searchIn),
776 (found - lastFound)+1);
777 outputposn = outputposn + (found - lastFound);
778 strcatW(outputposn, replacewith);
779 outputposn = outputposn + strlenW(replacewith);
780 lastFound = found + strlenW(searchFor);
782 strcatW(outputposn,
783 thisVarContents + (lastFound-searchIn));
784 strcatW(outputposn, s);
786 HeapFree(GetProcessHeap(), 0, s);
787 HeapFree(GetProcessHeap(), 0, searchIn);
788 HeapFree(GetProcessHeap(), 0, searchFor);
789 return start;
791 return start+1;
794 /*****************************************************************************
795 * Expand the command. Native expands lines from batch programs as they are
796 * read in and not again, except for 'for' variable substitution.
797 * eg. As evidence, "echo %1 && shift && echo %1" or "echo %%path%%"
799 static void handleExpansion(WCHAR *cmd, BOOL justFors,
800 const WCHAR *forVariable, const WCHAR *forValue) {
802 /* For commands in a context (batch program): */
803 /* Expand environment variables in a batch file %{0-9} first */
804 /* including support for any ~ modifiers */
805 /* Additionally: */
806 /* Expand the DATE, TIME, CD, RANDOM and ERRORLEVEL special */
807 /* names allowing environment variable overrides */
808 /* NOTE: To support the %PATH:xxx% syntax, also perform */
809 /* manual expansion of environment variables here */
811 WCHAR *p = cmd;
812 WCHAR *t;
813 int i;
815 while ((p = strchrW(p, '%'))) {
817 WINE_TRACE("Translate command:%s %d (at: %s)\n",
818 wine_dbgstr_w(cmd), justFors, wine_dbgstr_w(p));
819 i = *(p+1) - '0';
821 /* Don't touch %% unless its in Batch */
822 if (!justFors && *(p+1) == '%') {
823 if (context) {
824 WCMD_strsubstW(p, p+1, NULL, 0);
826 p+=1;
828 /* Replace %~ modifications if in batch program */
829 } else if (*(p+1) == '~') {
830 WCMD_HandleTildaModifiers(&p, forVariable, forValue, justFors);
831 p++;
833 /* Replace use of %0...%9 if in batch program*/
834 } else if (!justFors && context && (i >= 0) && (i <= 9)) {
835 t = WCMD_parameter(context -> command, i + context -> shift_count[i], NULL, NULL);
836 WCMD_strsubstW(p, p+2, t, -1);
838 /* Replace use of %* if in batch program*/
839 } else if (!justFors && context && *(p+1)=='*') {
840 WCHAR *startOfParms = NULL;
841 WCMD_parameter(context -> command, 1, &startOfParms, NULL);
842 if (startOfParms != NULL)
843 WCMD_strsubstW(p, p+2, startOfParms, -1);
844 else
845 WCMD_strsubstW(p, p+2, NULL, 0);
847 } else if (forVariable &&
848 (CompareStringW(LOCALE_USER_DEFAULT,
849 SORT_STRINGSORT,
851 strlenW(forVariable),
852 forVariable, -1) == CSTR_EQUAL)) {
853 WCMD_strsubstW(p, p + strlenW(forVariable), forValue, -1);
855 } else if (!justFors) {
856 p = WCMD_expand_envvar(p, forVariable, forValue);
858 /* In a FOR loop, see if this is the variable to replace */
859 } else { /* Ignore %'s on second pass of batch program */
860 p++;
864 return;
868 /*******************************************************************
869 * WCMD_parse - parse a command into parameters and qualifiers.
871 * On exit, all qualifiers are concatenated into q, the first string
872 * not beginning with "/" is in p1 and the
873 * second in p2. Any subsequent non-qualifier strings are lost.
874 * Parameters in quotes are handled.
876 static void WCMD_parse (const WCHAR *s, WCHAR *q, WCHAR *p1, WCHAR *p2)
878 int p = 0;
880 *q = *p1 = *p2 = '\0';
881 while (TRUE) {
882 switch (*s) {
883 case '/':
884 *q++ = *s++;
885 while ((*s != '\0') && (*s != ' ') && *s != '/') {
886 *q++ = toupperW (*s++);
888 *q = '\0';
889 break;
890 case ' ':
891 case '\t':
892 s++;
893 break;
894 case '"':
895 s++;
896 while ((*s != '\0') && (*s != '"')) {
897 if (p == 0) *p1++ = *s++;
898 else if (p == 1) *p2++ = *s++;
899 else s++;
901 if (p == 0) *p1 = '\0';
902 if (p == 1) *p2 = '\0';
903 p++;
904 if (*s == '"') s++;
905 break;
906 case '\0':
907 return;
908 default:
909 while ((*s != '\0') && (*s != ' ') && (*s != '\t')
910 && (*s != '=') && (*s != ',') ) {
911 if (p == 0) *p1++ = *s++;
912 else if (p == 1) *p2++ = *s++;
913 else s++;
915 /* Skip concurrent parms */
916 while ((*s == ' ') || (*s == '\t') || (*s == '=') || (*s == ',') ) s++;
918 if (p == 0) *p1 = '\0';
919 if (p == 1) *p2 = '\0';
920 p++;
925 static void init_msvcrt_io_block(STARTUPINFOW* st)
927 STARTUPINFOW st_p;
928 /* fetch the parent MSVCRT info block if any, so that the child can use the
929 * same handles as its grand-father
931 st_p.cb = sizeof(STARTUPINFOW);
932 GetStartupInfoW(&st_p);
933 st->cbReserved2 = st_p.cbReserved2;
934 st->lpReserved2 = st_p.lpReserved2;
935 if (st_p.cbReserved2 && st_p.lpReserved2)
937 /* Override the entries for fd 0,1,2 if we happened
938 * to change those std handles (this depends on the way cmd sets
939 * its new input & output handles)
941 size_t sz = max(sizeof(unsigned) + (sizeof(char) + sizeof(HANDLE)) * 3, st_p.cbReserved2);
942 BYTE* ptr = HeapAlloc(GetProcessHeap(), 0, sz);
943 if (ptr)
945 unsigned num = *(unsigned*)st_p.lpReserved2;
946 char* flags = (char*)(ptr + sizeof(unsigned));
947 HANDLE* handles = (HANDLE*)(flags + num * sizeof(char));
949 memcpy(ptr, st_p.lpReserved2, st_p.cbReserved2);
950 st->cbReserved2 = sz;
951 st->lpReserved2 = ptr;
953 #define WX_OPEN 0x01 /* see dlls/msvcrt/file.c */
954 if (num <= 0 || (flags[0] & WX_OPEN))
956 handles[0] = GetStdHandle(STD_INPUT_HANDLE);
957 flags[0] |= WX_OPEN;
959 if (num <= 1 || (flags[1] & WX_OPEN))
961 handles[1] = GetStdHandle(STD_OUTPUT_HANDLE);
962 flags[1] |= WX_OPEN;
964 if (num <= 2 || (flags[2] & WX_OPEN))
966 handles[2] = GetStdHandle(STD_ERROR_HANDLE);
967 flags[2] |= WX_OPEN;
969 #undef WX_OPEN
974 /******************************************************************************
975 * WCMD_run_program
977 * Execute a command line as an external program. Must allow recursion.
979 * Precedence:
980 * Manual testing under windows shows PATHEXT plays a key part in this,
981 * and the search algorithm and precedence appears to be as follows.
983 * Search locations:
984 * If directory supplied on command, just use that directory
985 * If extension supplied on command, look for that explicit name first
986 * Otherwise, search in each directory on the path
987 * Precedence:
988 * If extension supplied on command, look for that explicit name first
989 * Then look for supplied name .* (even if extension supplied, so
990 * 'garbage.exe' will match 'garbage.exe.cmd')
991 * If any found, cycle through PATHEXT looking for name.exe one by one
992 * Launching
993 * Once a match has been found, it is launched - Code currently uses
994 * findexecutable to achieve this which is left untouched.
997 void WCMD_run_program (WCHAR *command, int called) {
999 WCHAR temp[MAX_PATH];
1000 WCHAR pathtosearch[MAXSTRING];
1001 WCHAR *pathposn;
1002 WCHAR stemofsearch[MAX_PATH]; /* maximum allowed executable name is
1003 MAX_PATH, including null character */
1004 WCHAR *lastSlash;
1005 WCHAR pathext[MAXSTRING];
1006 BOOL extensionsupplied = FALSE;
1007 BOOL launched = FALSE;
1008 BOOL status;
1009 BOOL assumeInternal = FALSE;
1010 DWORD len;
1011 static const WCHAR envPath[] = {'P','A','T','H','\0'};
1012 static const WCHAR envPathExt[] = {'P','A','T','H','E','X','T','\0'};
1013 static const WCHAR delims[] = {'/','\\',':','\0'};
1015 /* Quick way to get the filename
1016 * (but handle leading / as part of program name, not qualifier)
1018 for (len = 0; command[len] == '/'; len++) param1[len] = '/';
1019 WCMD_parse (command + len, quals, param1 + len, param2);
1021 if (!(*param1) && !(*param2))
1022 return;
1024 /* Calculate the search path and stem to search for */
1025 if (strpbrkW (param1, delims) == NULL) { /* No explicit path given, search path */
1026 static const WCHAR curDir[] = {'.',';','\0'};
1027 strcpyW(pathtosearch, curDir);
1028 len = GetEnvironmentVariableW(envPath, &pathtosearch[2], (sizeof(pathtosearch)/sizeof(WCHAR))-2);
1029 if ((len == 0) || (len >= (sizeof(pathtosearch)/sizeof(WCHAR)) - 2)) {
1030 static const WCHAR curDir[] = {'.','\0'};
1031 strcpyW (pathtosearch, curDir);
1033 if (strchrW(param1, '.') != NULL) extensionsupplied = TRUE;
1034 if (strlenW(param1) >= MAX_PATH)
1036 WCMD_output_asis_stderr(WCMD_LoadMessage(WCMD_LINETOOLONG));
1037 return;
1040 strcpyW(stemofsearch, param1);
1042 } else {
1044 /* Convert eg. ..\fred to include a directory by removing file part */
1045 GetFullPathNameW(param1, sizeof(pathtosearch)/sizeof(WCHAR), pathtosearch, NULL);
1046 lastSlash = strrchrW(pathtosearch, '\\');
1047 if (lastSlash && strchrW(lastSlash, '.') != NULL) extensionsupplied = TRUE;
1048 strcpyW(stemofsearch, lastSlash+1);
1050 /* Reduce pathtosearch to a path with trailing '\' to support c:\a.bat and
1051 c:\windows\a.bat syntax */
1052 if (lastSlash) *(lastSlash + 1) = 0x00;
1055 /* Now extract PATHEXT */
1056 len = GetEnvironmentVariableW(envPathExt, pathext, sizeof(pathext)/sizeof(WCHAR));
1057 if ((len == 0) || (len >= (sizeof(pathext)/sizeof(WCHAR)))) {
1058 static const WCHAR dfltPathExt[] = {'.','b','a','t',';',
1059 '.','c','o','m',';',
1060 '.','c','m','d',';',
1061 '.','e','x','e','\0'};
1062 strcpyW (pathext, dfltPathExt);
1065 /* Loop through the search path, dir by dir */
1066 pathposn = pathtosearch;
1067 WINE_TRACE("Searching in '%s' for '%s'\n", wine_dbgstr_w(pathtosearch),
1068 wine_dbgstr_w(stemofsearch));
1069 while (!launched && pathposn) {
1071 WCHAR thisDir[MAX_PATH] = {'\0'};
1072 WCHAR *pos = NULL;
1073 BOOL found = FALSE;
1075 /* Work on the first directory on the search path */
1076 pos = strchrW(pathposn, ';');
1077 if (pos) {
1078 memcpy(thisDir, pathposn, (pos-pathposn) * sizeof(WCHAR));
1079 thisDir[(pos-pathposn)] = 0x00;
1080 pathposn = pos+1;
1082 } else {
1083 strcpyW(thisDir, pathposn);
1084 pathposn = NULL;
1087 /* Since you can have eg. ..\.. on the path, need to expand
1088 to full information */
1089 strcpyW(temp, thisDir);
1090 GetFullPathNameW(temp, MAX_PATH, thisDir, NULL);
1092 /* 1. If extension supplied, see if that file exists */
1093 strcatW(thisDir, slashW);
1094 strcatW(thisDir, stemofsearch);
1095 pos = &thisDir[strlenW(thisDir)]; /* Pos = end of name */
1097 /* 1. If extension supplied, see if that file exists */
1098 if (extensionsupplied) {
1099 if (GetFileAttributesW(thisDir) != INVALID_FILE_ATTRIBUTES) {
1100 found = TRUE;
1104 /* 2. Any .* matches? */
1105 if (!found) {
1106 HANDLE h;
1107 WIN32_FIND_DATAW finddata;
1108 static const WCHAR allFiles[] = {'.','*','\0'};
1110 strcatW(thisDir,allFiles);
1111 h = FindFirstFileW(thisDir, &finddata);
1112 FindClose(h);
1113 if (h != INVALID_HANDLE_VALUE) {
1115 WCHAR *thisExt = pathext;
1117 /* 3. Yes - Try each path ext */
1118 while (thisExt) {
1119 WCHAR *nextExt = strchrW(thisExt, ';');
1121 if (nextExt) {
1122 memcpy(pos, thisExt, (nextExt-thisExt) * sizeof(WCHAR));
1123 pos[(nextExt-thisExt)] = 0x00;
1124 thisExt = nextExt+1;
1125 } else {
1126 strcpyW(pos, thisExt);
1127 thisExt = NULL;
1130 if (GetFileAttributesW(thisDir) != INVALID_FILE_ATTRIBUTES) {
1131 found = TRUE;
1132 thisExt = NULL;
1138 /* Internal programs won't be picked up by this search, so even
1139 though not found, try one last createprocess and wait for it
1140 to complete.
1141 Note: Ideally we could tell between a console app (wait) and a
1142 windows app, but the API's for it fail in this case */
1143 if (!found && pathposn == NULL) {
1144 WINE_TRACE("ASSUMING INTERNAL\n");
1145 assumeInternal = TRUE;
1146 } else {
1147 WINE_TRACE("Found as %s\n", wine_dbgstr_w(thisDir));
1150 /* Once found, launch it */
1151 if (found || assumeInternal) {
1152 STARTUPINFOW st;
1153 PROCESS_INFORMATION pe;
1154 SHFILEINFOW psfi;
1155 DWORD console;
1156 HINSTANCE hinst;
1157 WCHAR *ext = strrchrW( thisDir, '.' );
1158 static const WCHAR batExt[] = {'.','b','a','t','\0'};
1159 static const WCHAR cmdExt[] = {'.','c','m','d','\0'};
1161 launched = TRUE;
1163 /* Special case BAT and CMD */
1164 if (ext && (!strcmpiW(ext, batExt) || !strcmpiW(ext, cmdExt))) {
1165 WCMD_batch (thisDir, command, called, NULL, INVALID_HANDLE_VALUE);
1166 return;
1167 } else {
1169 /* thisDir contains the file to be launched, but with what?
1170 eg. a.exe will require a.exe to be launched, a.html may be iexplore */
1171 hinst = FindExecutableW (thisDir, NULL, temp);
1172 if ((INT_PTR)hinst < 32)
1173 console = 0;
1174 else
1175 console = SHGetFileInfoW(temp, 0, &psfi, sizeof(psfi), SHGFI_EXETYPE);
1177 ZeroMemory (&st, sizeof(STARTUPINFOW));
1178 st.cb = sizeof(STARTUPINFOW);
1179 init_msvcrt_io_block(&st);
1181 /* Launch the process and if a CUI wait on it to complete
1182 Note: Launching internal wine processes cannot specify a full path to exe */
1183 status = CreateProcessW(assumeInternal?NULL : thisDir,
1184 command, NULL, NULL, TRUE, 0, NULL, NULL, &st, &pe);
1185 if ((opt_c || opt_k) && !opt_s && !status
1186 && GetLastError()==ERROR_FILE_NOT_FOUND && command[0]=='\"') {
1187 /* strip first and last quote WCHARacters and try again */
1188 WCMD_strip_quotes(command);
1189 opt_s = TRUE;
1190 WCMD_run_program(command, called);
1191 return;
1194 if (!status)
1195 break;
1197 if (!assumeInternal && !console) errorlevel = 0;
1198 else
1200 /* Always wait when called in a batch program context */
1201 if (assumeInternal || context || !HIWORD(console)) WaitForSingleObject (pe.hProcess, INFINITE);
1202 GetExitCodeProcess (pe.hProcess, &errorlevel);
1203 if (errorlevel == STILL_ACTIVE) errorlevel = 0;
1205 CloseHandle(pe.hProcess);
1206 CloseHandle(pe.hThread);
1207 return;
1212 /* Not found anywhere - give up */
1213 SetLastError(ERROR_FILE_NOT_FOUND);
1214 WCMD_print_error ();
1216 /* If a command fails to launch, it sets errorlevel 9009 - which
1217 does not seem to have any associated constant definition */
1218 errorlevel = 9009;
1219 return;
1223 /*****************************************************************************
1224 * Process one command. If the command is EXIT this routine does not return.
1225 * We will recurse through here executing batch files.
1227 void WCMD_execute (const WCHAR *command, const WCHAR *redirects,
1228 const WCHAR *forVariable, const WCHAR *forValue,
1229 CMD_LIST **cmdList)
1231 WCHAR *cmd, *p, *redir;
1232 int status, i;
1233 DWORD count, creationDisposition;
1234 HANDLE h;
1235 WCHAR *whichcmd;
1236 SECURITY_ATTRIBUTES sa;
1237 WCHAR *new_cmd = NULL;
1238 WCHAR *new_redir = NULL;
1239 HANDLE old_stdhandles[3] = {GetStdHandle (STD_INPUT_HANDLE),
1240 GetStdHandle (STD_OUTPUT_HANDLE),
1241 GetStdHandle (STD_ERROR_HANDLE)};
1242 DWORD idx_stdhandles[3] = {STD_INPUT_HANDLE,
1243 STD_OUTPUT_HANDLE,
1244 STD_ERROR_HANDLE};
1245 BOOL prev_echo_mode, piped = FALSE;
1247 WINE_TRACE("command on entry:%s (%p), with forVariable '%s'='%s'\n",
1248 wine_dbgstr_w(command), cmdList,
1249 wine_dbgstr_w(forVariable), wine_dbgstr_w(forValue));
1251 /* If the next command is a pipe then we implement pipes by redirecting
1252 the output from this command to a temp file and input into the
1253 next command from that temp file.
1254 FIXME: Use of named pipes would make more sense here as currently this
1255 process has to finish before the next one can start but this requires
1256 a change to not wait for the first app to finish but rather the pipe */
1257 if (cmdList && (*cmdList)->nextcommand &&
1258 (*cmdList)->nextcommand->prevDelim == CMD_PIPE) {
1260 WCHAR temp_path[MAX_PATH];
1261 static const WCHAR cmdW[] = {'C','M','D','\0'};
1263 /* Remember piping is in action */
1264 WINE_TRACE("Output needs to be piped\n");
1265 piped = TRUE;
1267 /* Generate a unique temporary filename */
1268 GetTempPathW(sizeof(temp_path)/sizeof(WCHAR), temp_path);
1269 GetTempFileNameW(temp_path, cmdW, 0, (*cmdList)->nextcommand->pipeFile);
1270 WINE_TRACE("Using temporary file of %s\n",
1271 wine_dbgstr_w((*cmdList)->nextcommand->pipeFile));
1274 /* Move copy of the command onto the heap so it can be expanded */
1275 new_cmd = HeapAlloc( GetProcessHeap(), 0, MAXSTRING * sizeof(WCHAR));
1276 if (!new_cmd)
1278 WINE_ERR("Could not allocate memory for new_cmd\n");
1279 return;
1281 strcpyW(new_cmd, command);
1283 /* Move copy of the redirects onto the heap so it can be expanded */
1284 new_redir = HeapAlloc( GetProcessHeap(), 0, MAXSTRING * sizeof(WCHAR));
1285 if (!new_redir)
1287 WINE_ERR("Could not allocate memory for new_redir\n");
1288 HeapFree( GetProcessHeap(), 0, new_cmd );
1289 return;
1292 /* If piped output, send stdout to the pipe by appending >filename to redirects */
1293 if (piped) {
1294 static const WCHAR redirOut[] = {'%','s',' ','>',' ','%','s','\0'};
1295 wsprintfW (new_redir, redirOut, redirects, (*cmdList)->nextcommand->pipeFile);
1296 WINE_TRACE("Redirects now %s\n", wine_dbgstr_w(new_redir));
1297 } else {
1298 strcpyW(new_redir, redirects);
1301 /* Expand variables in command line mode only (batch mode will
1302 be expanded as the line is read in, except for 'for' loops) */
1303 handleExpansion(new_cmd, (context != NULL), forVariable, forValue);
1304 handleExpansion(new_redir, (context != NULL), forVariable, forValue);
1305 cmd = new_cmd;
1308 * Changing default drive has to be handled as a special case.
1311 if ((cmd[1] == ':') && IsCharAlphaW(cmd[0]) && (strlenW(cmd) == 2)) {
1312 WCHAR envvar[5];
1313 WCHAR dir[MAX_PATH];
1315 /* According to MSDN CreateProcess docs, special env vars record
1316 the current directory on each drive, in the form =C:
1317 so see if one specified, and if so go back to it */
1318 strcpyW(envvar, equalW);
1319 strcatW(envvar, cmd);
1320 if (GetEnvironmentVariableW(envvar, dir, MAX_PATH) == 0) {
1321 static const WCHAR fmt[] = {'%','s','\\','\0'};
1322 wsprintfW(cmd, fmt, cmd);
1323 WINE_TRACE("No special directory settings, using dir of %s\n", wine_dbgstr_w(cmd));
1325 WINE_TRACE("Got directory %s as %s\n", wine_dbgstr_w(envvar), wine_dbgstr_w(cmd));
1326 status = SetCurrentDirectoryW(cmd);
1327 if (!status) WCMD_print_error ();
1328 HeapFree( GetProcessHeap(), 0, cmd );
1329 HeapFree( GetProcessHeap(), 0, new_redir );
1330 return;
1333 sa.nLength = sizeof(sa);
1334 sa.lpSecurityDescriptor = NULL;
1335 sa.bInheritHandle = TRUE;
1338 * Redirect stdin, stdout and/or stderr if required.
1341 /* STDIN could come from a preceding pipe, so delete on close if it does */
1342 if (cmdList && (*cmdList)->pipeFile[0] != 0x00) {
1343 WINE_TRACE("Input coming from %s\n", wine_dbgstr_w((*cmdList)->pipeFile));
1344 h = CreateFileW((*cmdList)->pipeFile, GENERIC_READ,
1345 FILE_SHARE_READ, &sa, OPEN_EXISTING,
1346 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE, NULL);
1347 if (h == INVALID_HANDLE_VALUE) {
1348 WCMD_print_error ();
1349 HeapFree( GetProcessHeap(), 0, cmd );
1350 HeapFree( GetProcessHeap(), 0, new_redir );
1351 return;
1353 SetStdHandle (STD_INPUT_HANDLE, h);
1355 /* No need to remember the temporary name any longer once opened */
1356 (*cmdList)->pipeFile[0] = 0x00;
1358 /* Otherwise STDIN could come from a '<' redirect */
1359 } else if ((p = strchrW(new_redir,'<')) != NULL) {
1360 h = CreateFileW(WCMD_parameter(++p, 0, NULL, NULL), GENERIC_READ, FILE_SHARE_READ,
1361 &sa, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
1362 if (h == INVALID_HANDLE_VALUE) {
1363 WCMD_print_error ();
1364 HeapFree( GetProcessHeap(), 0, cmd );
1365 HeapFree( GetProcessHeap(), 0, new_redir );
1366 return;
1368 SetStdHandle (STD_INPUT_HANDLE, h);
1371 /* Scan the whole command looking for > and 2> */
1372 redir = new_redir;
1373 while (redir != NULL && ((p = strchrW(redir,'>')) != NULL)) {
1374 int handle = 0;
1376 if (p > redir && (*(p-1)=='2'))
1377 handle = 2;
1378 else
1379 handle = 1;
1381 p++;
1382 if ('>' == *p) {
1383 creationDisposition = OPEN_ALWAYS;
1384 p++;
1386 else {
1387 creationDisposition = CREATE_ALWAYS;
1390 /* Add support for 2>&1 */
1391 redir = p;
1392 if (*p == '&') {
1393 int idx = *(p+1) - '0';
1395 if (DuplicateHandle(GetCurrentProcess(),
1396 GetStdHandle(idx_stdhandles[idx]),
1397 GetCurrentProcess(),
1399 0, TRUE, DUPLICATE_SAME_ACCESS) == 0) {
1400 WINE_FIXME("Duplicating handle failed with gle %d\n", GetLastError());
1402 WINE_TRACE("Redirect %d (%p) to %d (%p)\n", handle, GetStdHandle(idx_stdhandles[idx]), idx, h);
1404 } else {
1405 WCHAR *param = WCMD_parameter(p, 0, NULL, NULL);
1406 h = CreateFileW(param, GENERIC_WRITE, 0, &sa, creationDisposition,
1407 FILE_ATTRIBUTE_NORMAL, NULL);
1408 if (h == INVALID_HANDLE_VALUE) {
1409 WCMD_print_error ();
1410 HeapFree( GetProcessHeap(), 0, cmd );
1411 HeapFree( GetProcessHeap(), 0, new_redir );
1412 return;
1414 if (SetFilePointer (h, 0, NULL, FILE_END) ==
1415 INVALID_SET_FILE_POINTER) {
1416 WCMD_print_error ();
1418 WINE_TRACE("Redirect %d to '%s' (%p)\n", handle, wine_dbgstr_w(param), h);
1421 SetStdHandle (idx_stdhandles[handle], h);
1425 * Strip leading whitespaces, and a '@' if supplied
1427 whichcmd = WCMD_skip_leading_spaces(cmd);
1428 WINE_TRACE("Command: '%s'\n", wine_dbgstr_w(cmd));
1429 if (whichcmd[0] == '@') whichcmd++;
1432 * Check if the command entered is internal. If it is, pass the rest of the
1433 * line down to the command. If not try to run a program.
1436 count = 0;
1437 while (IsCharAlphaNumericW(whichcmd[count])) {
1438 count++;
1440 for (i=0; i<=WCMD_EXIT; i++) {
1441 if (CompareStringW(LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
1442 whichcmd, count, inbuilt[i], -1) == CSTR_EQUAL) break;
1444 p = WCMD_skip_leading_spaces (&whichcmd[count]);
1445 WCMD_parse (p, quals, param1, param2);
1446 WINE_TRACE("param1: %s, param2: %s\n", wine_dbgstr_w(param1), wine_dbgstr_w(param2));
1448 if (i <= WCMD_EXIT && (p[0] == '/') && (p[1] == '?')) {
1449 /* this is a help request for a builtin program */
1450 i = WCMD_HELP;
1451 memcpy(p, whichcmd, count * sizeof(WCHAR));
1452 p[count] = '\0';
1456 switch (i) {
1458 case WCMD_CALL:
1459 WCMD_call (p);
1460 break;
1461 case WCMD_CD:
1462 case WCMD_CHDIR:
1463 WCMD_setshow_default (p);
1464 break;
1465 case WCMD_CLS:
1466 WCMD_clear_screen ();
1467 break;
1468 case WCMD_COPY:
1469 WCMD_copy ();
1470 break;
1471 case WCMD_CTTY:
1472 WCMD_change_tty ();
1473 break;
1474 case WCMD_DATE:
1475 WCMD_setshow_date ();
1476 break;
1477 case WCMD_DEL:
1478 case WCMD_ERASE:
1479 WCMD_delete (p);
1480 break;
1481 case WCMD_DIR:
1482 WCMD_directory (p);
1483 break;
1484 case WCMD_ECHO:
1485 WCMD_echo(&whichcmd[count]);
1486 break;
1487 case WCMD_FOR:
1488 WCMD_for (p, cmdList);
1489 break;
1490 case WCMD_GOTO:
1491 WCMD_goto (cmdList);
1492 break;
1493 case WCMD_HELP:
1494 WCMD_give_help (p);
1495 break;
1496 case WCMD_IF:
1497 WCMD_if (p, cmdList);
1498 break;
1499 case WCMD_LABEL:
1500 WCMD_volume (TRUE, p);
1501 break;
1502 case WCMD_MD:
1503 case WCMD_MKDIR:
1504 WCMD_create_dir (p);
1505 break;
1506 case WCMD_MOVE:
1507 WCMD_move ();
1508 break;
1509 case WCMD_PATH:
1510 WCMD_setshow_path (p);
1511 break;
1512 case WCMD_PAUSE:
1513 WCMD_pause ();
1514 break;
1515 case WCMD_PROMPT:
1516 WCMD_setshow_prompt ();
1517 break;
1518 case WCMD_REM:
1519 break;
1520 case WCMD_REN:
1521 case WCMD_RENAME:
1522 WCMD_rename ();
1523 break;
1524 case WCMD_RD:
1525 case WCMD_RMDIR:
1526 WCMD_remove_dir (p);
1527 break;
1528 case WCMD_SETLOCAL:
1529 WCMD_setlocal(p);
1530 break;
1531 case WCMD_ENDLOCAL:
1532 WCMD_endlocal();
1533 break;
1534 case WCMD_SET:
1535 WCMD_setshow_env (p);
1536 break;
1537 case WCMD_SHIFT:
1538 WCMD_shift (p);
1539 break;
1540 case WCMD_TIME:
1541 WCMD_setshow_time ();
1542 break;
1543 case WCMD_TITLE:
1544 if (strlenW(&whichcmd[count]) > 0)
1545 WCMD_title(&whichcmd[count+1]);
1546 break;
1547 case WCMD_TYPE:
1548 WCMD_type (p);
1549 break;
1550 case WCMD_VER:
1551 WCMD_output_asis(newline);
1552 WCMD_version ();
1553 break;
1554 case WCMD_VERIFY:
1555 WCMD_verify (p);
1556 break;
1557 case WCMD_VOL:
1558 WCMD_volume (FALSE, p);
1559 break;
1560 case WCMD_PUSHD:
1561 WCMD_pushd(p);
1562 break;
1563 case WCMD_POPD:
1564 WCMD_popd();
1565 break;
1566 case WCMD_ASSOC:
1567 WCMD_assoc(p, TRUE);
1568 break;
1569 case WCMD_COLOR:
1570 WCMD_color();
1571 break;
1572 case WCMD_FTYPE:
1573 WCMD_assoc(p, FALSE);
1574 break;
1575 case WCMD_MORE:
1576 WCMD_more(p);
1577 break;
1578 case WCMD_CHOICE:
1579 WCMD_choice(p);
1580 break;
1581 case WCMD_EXIT:
1582 WCMD_exit (cmdList);
1583 break;
1584 default:
1585 prev_echo_mode = echo_mode;
1586 WCMD_run_program (whichcmd, 0);
1587 echo_mode = prev_echo_mode;
1589 HeapFree( GetProcessHeap(), 0, cmd );
1590 HeapFree( GetProcessHeap(), 0, new_redir );
1592 /* Restore old handles */
1593 for (i=0; i<3; i++) {
1594 if (old_stdhandles[i] != GetStdHandle(idx_stdhandles[i])) {
1595 CloseHandle (GetStdHandle (idx_stdhandles[i]));
1596 SetStdHandle (idx_stdhandles[i], old_stdhandles[i]);
1601 /*************************************************************************
1602 * WCMD_LoadMessage
1603 * Load a string from the resource file, handling any error
1604 * Returns string retrieved from resource file
1606 WCHAR *WCMD_LoadMessage(UINT id) {
1607 static WCHAR msg[2048];
1608 static const WCHAR failedMsg[] = {'F','a','i','l','e','d','!','\0'};
1610 if (!LoadStringW(GetModuleHandleW(NULL), id, msg, sizeof(msg)/sizeof(WCHAR))) {
1611 WINE_FIXME("LoadString failed with %d\n", GetLastError());
1612 strcpyW(msg, failedMsg);
1614 return msg;
1617 /***************************************************************************
1618 * WCMD_DumpCommands
1620 * Dumps out the parsed command line to ensure syntax is correct
1622 static void WCMD_DumpCommands(CMD_LIST *commands) {
1623 CMD_LIST *thisCmd = commands;
1625 WINE_TRACE("Parsed line:\n");
1626 while (thisCmd != NULL) {
1627 WINE_TRACE("%p %d %2.2d %p %s Redir:%s\n",
1628 thisCmd,
1629 thisCmd->prevDelim,
1630 thisCmd->bracketDepth,
1631 thisCmd->nextcommand,
1632 wine_dbgstr_w(thisCmd->command),
1633 wine_dbgstr_w(thisCmd->redirects));
1634 thisCmd = thisCmd->nextcommand;
1638 /***************************************************************************
1639 * WCMD_addCommand
1641 * Adds a command to the current command list
1643 static void WCMD_addCommand(WCHAR *command, int *commandLen,
1644 WCHAR *redirs, int *redirLen,
1645 WCHAR **copyTo, int **copyToLen,
1646 CMD_DELIMITERS prevDelim, int curDepth,
1647 CMD_LIST **lastEntry, CMD_LIST **output) {
1649 CMD_LIST *thisEntry = NULL;
1651 /* Allocate storage for command */
1652 thisEntry = HeapAlloc(GetProcessHeap(), 0, sizeof(CMD_LIST));
1654 /* Copy in the command */
1655 if (command) {
1656 thisEntry->command = HeapAlloc(GetProcessHeap(), 0,
1657 (*commandLen+1) * sizeof(WCHAR));
1658 memcpy(thisEntry->command, command, *commandLen * sizeof(WCHAR));
1659 thisEntry->command[*commandLen] = 0x00;
1661 /* Copy in the redirects */
1662 thisEntry->redirects = HeapAlloc(GetProcessHeap(), 0,
1663 (*redirLen+1) * sizeof(WCHAR));
1664 memcpy(thisEntry->redirects, redirs, *redirLen * sizeof(WCHAR));
1665 thisEntry->redirects[*redirLen] = 0x00;
1666 thisEntry->pipeFile[0] = 0x00;
1668 /* Reset the lengths */
1669 *commandLen = 0;
1670 *redirLen = 0;
1671 *copyToLen = commandLen;
1672 *copyTo = command;
1674 } else {
1675 thisEntry->command = NULL;
1676 thisEntry->redirects = NULL;
1677 thisEntry->pipeFile[0] = 0x00;
1680 /* Fill in other fields */
1681 thisEntry->nextcommand = NULL;
1682 thisEntry->prevDelim = prevDelim;
1683 thisEntry->bracketDepth = curDepth;
1684 if (*lastEntry) {
1685 (*lastEntry)->nextcommand = thisEntry;
1686 } else {
1687 *output = thisEntry;
1689 *lastEntry = thisEntry;
1693 /***************************************************************************
1694 * WCMD_IsEndQuote
1696 * Checks if the quote pointed to is the end-quote.
1698 * Quotes end if:
1700 * 1) The current parameter ends at EOL or at the beginning
1701 * of a redirection or pipe and not in a quote section.
1703 * 2) If the next character is a space and not in a quote section.
1705 * Returns TRUE if this is an end quote, and FALSE if it is not.
1708 static BOOL WCMD_IsEndQuote(const WCHAR *quote, int quoteIndex)
1710 int quoteCount = quoteIndex;
1711 int i;
1713 /* If we are not in a quoted section, then we are not an end-quote */
1714 if(quoteIndex == 0)
1716 return FALSE;
1719 /* Check how many quotes are left for this parameter */
1720 for(i=0;quote[i];i++)
1722 if(quote[i] == '"')
1724 quoteCount++;
1727 /* Quote counting ends at EOL, redirection, space or pipe if current quote is complete */
1728 else if(((quoteCount % 2) == 0)
1729 && ((quote[i] == '<') || (quote[i] == '>') || (quote[i] == '|') || (quote[i] == ' ')))
1731 break;
1735 /* If the quote is part of the last part of a series of quotes-on-quotes, then it must
1736 be an end-quote */
1737 if(quoteIndex >= (quoteCount / 2))
1739 return TRUE;
1742 /* No cigar */
1743 return FALSE;
1746 /***************************************************************************
1747 * WCMD_ReadAndParseLine
1749 * Either uses supplied input or
1750 * Reads a file from the handle, and then...
1751 * Parse the text buffer, splitting into separate commands
1752 * - unquoted && strings split 2 commands but the 2nd is flagged as
1753 * following an &&
1754 * - ( as the first character just ups the bracket depth
1755 * - unquoted ) when bracket depth > 0 terminates a bracket and
1756 * adds a CMD_LIST structure with null command
1757 * - Anything else gets put into the command string (including
1758 * redirects)
1760 WCHAR *WCMD_ReadAndParseLine(const WCHAR *optionalcmd, CMD_LIST **output, HANDLE readFrom)
1762 WCHAR *curPos;
1763 int inQuotes = 0;
1764 WCHAR curString[MAXSTRING];
1765 int curStringLen = 0;
1766 WCHAR curRedirs[MAXSTRING];
1767 int curRedirsLen = 0;
1768 WCHAR *curCopyTo;
1769 int *curLen;
1770 int curDepth = 0;
1771 CMD_LIST *lastEntry = NULL;
1772 CMD_DELIMITERS prevDelim = CMD_NONE;
1773 static WCHAR *extraSpace = NULL; /* Deliberately never freed */
1774 static const WCHAR remCmd[] = {'r','e','m'};
1775 static const WCHAR forCmd[] = {'f','o','r'};
1776 static const WCHAR ifCmd[] = {'i','f'};
1777 static const WCHAR ifElse[] = {'e','l','s','e'};
1778 BOOL inRem = FALSE;
1779 BOOL inFor = FALSE;
1780 BOOL inIn = FALSE;
1781 BOOL inIf = FALSE;
1782 BOOL inElse= FALSE;
1783 BOOL onlyWhiteSpace = FALSE;
1784 BOOL lastWasWhiteSpace = FALSE;
1785 BOOL lastWasDo = FALSE;
1786 BOOL lastWasIn = FALSE;
1787 BOOL lastWasElse = FALSE;
1788 BOOL lastWasRedirect = TRUE;
1790 /* Allocate working space for a command read from keyboard, file etc */
1791 if (!extraSpace)
1792 extraSpace = HeapAlloc(GetProcessHeap(), 0, (MAXSTRING+1) * sizeof(WCHAR));
1793 if (!extraSpace)
1795 WINE_ERR("Could not allocate memory for extraSpace\n");
1796 return NULL;
1799 /* If initial command read in, use that, otherwise get input from handle */
1800 if (optionalcmd != NULL) {
1801 strcpyW(extraSpace, optionalcmd);
1802 } else if (readFrom == INVALID_HANDLE_VALUE) {
1803 WINE_FIXME("No command nor handle supplied\n");
1804 } else {
1805 if (!WCMD_fgets(extraSpace, MAXSTRING, readFrom))
1806 return NULL;
1808 curPos = extraSpace;
1810 /* Handle truncated input - issue warning */
1811 if (strlenW(extraSpace) == MAXSTRING -1) {
1812 WCMD_output_asis_stderr(WCMD_LoadMessage(WCMD_TRUNCATEDLINE));
1813 WCMD_output_asis_stderr(extraSpace);
1814 WCMD_output_asis_stderr(newline);
1817 /* Replace env vars if in a batch context */
1818 if (context) handleExpansion(extraSpace, FALSE, NULL, NULL);
1819 /* Show prompt before batch line IF echo is on and in batch program */
1820 if (context && echo_mode && extraSpace[0] && (extraSpace[0] != '@')) {
1821 static const WCHAR echoDot[] = {'e','c','h','o','.'};
1822 static const WCHAR echoCol[] = {'e','c','h','o',':'};
1823 const DWORD len = sizeof(echoDot)/sizeof(echoDot[0]);
1824 DWORD curr_size = strlenW(extraSpace);
1825 DWORD min_len = (curr_size < len ? curr_size : len);
1826 WCMD_show_prompt();
1827 WCMD_output_asis(extraSpace);
1828 /* I don't know why Windows puts a space here but it does */
1829 /* Except for lines starting with 'echo.' or 'echo:'. Ask MS why */
1830 if (CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
1831 extraSpace, min_len, echoDot, len) != CSTR_EQUAL
1832 && CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
1833 extraSpace, min_len, echoCol, len) != CSTR_EQUAL)
1835 WCMD_output_asis(space);
1837 WCMD_output_asis(newline);
1840 /* Start with an empty string, copying to the command string */
1841 curStringLen = 0;
1842 curRedirsLen = 0;
1843 curCopyTo = curString;
1844 curLen = &curStringLen;
1845 lastWasRedirect = FALSE; /* Required for eg spaces between > and filename */
1847 /* Parse every character on the line being processed */
1848 while (*curPos != 0x00) {
1850 WCHAR thisChar;
1852 /* Debugging AID:
1853 WINE_TRACE("Looking at '%c' (len:%d, lws:%d, ows:%d)\n", *curPos, *curLen,
1854 lastWasWhiteSpace, onlyWhiteSpace);
1857 /* Certain commands need special handling */
1858 if (curStringLen == 0 && curCopyTo == curString) {
1859 static const WCHAR forDO[] = {'d','o'};
1861 /* If command starts with 'rem ', ignore any &&, ( etc. */
1862 if (WCMD_keyword_ws_found(remCmd, sizeof(remCmd)/sizeof(remCmd[0]), curPos)) {
1863 inRem = TRUE;
1865 } else if (WCMD_keyword_ws_found(forCmd, sizeof(forCmd)/sizeof(forCmd[0]), curPos)) {
1866 inFor = TRUE;
1868 /* If command starts with 'if ' or 'else ', handle ('s mid line. We should ensure this
1869 is only true in the command portion of the IF statement, but this
1870 should suffice for now
1871 FIXME: Silly syntax like "if 1(==1( (
1872 echo they equal
1873 )" will be parsed wrong */
1874 } else if (WCMD_keyword_ws_found(ifCmd, sizeof(ifCmd)/sizeof(ifCmd[0]), curPos)) {
1875 inIf = TRUE;
1877 } else if (WCMD_keyword_ws_found(ifElse, sizeof(ifElse)/sizeof(ifElse[0]), curPos)) {
1878 const int keyw_len = sizeof(ifElse)/sizeof(ifElse[0]) + 1;
1879 inElse = TRUE;
1880 lastWasElse = TRUE;
1881 onlyWhiteSpace = TRUE;
1882 memcpy(&curCopyTo[*curLen], curPos, keyw_len*sizeof(WCHAR));
1883 (*curLen)+=keyw_len;
1884 curPos+=keyw_len;
1885 continue;
1887 /* In a for loop, the DO command will follow a close bracket followed by
1888 whitespace, followed by DO, ie closeBracket inserts a NULL entry, curLen
1889 is then 0, and all whitespace is skipped */
1890 } else if (inFor &&
1891 WCMD_keyword_ws_found(forDO, sizeof(forDO)/sizeof(forDO[0]), curPos)) {
1892 const int keyw_len = sizeof(forDO)/sizeof(forDO[0]) + 1;
1893 WINE_TRACE("Found 'DO '\n");
1894 lastWasDo = TRUE;
1895 onlyWhiteSpace = TRUE;
1896 memcpy(&curCopyTo[*curLen], curPos, keyw_len*sizeof(WCHAR));
1897 (*curLen)+=keyw_len;
1898 curPos+=keyw_len;
1899 continue;
1901 } else if (curCopyTo == curString) {
1903 /* Special handling for the 'FOR' command */
1904 if (inFor && lastWasWhiteSpace) {
1905 static const WCHAR forIN[] = {'i','n'};
1907 WINE_TRACE("Found 'FOR ', comparing next parm: '%s'\n", wine_dbgstr_w(curPos));
1909 if (WCMD_keyword_ws_found(forIN, sizeof(forIN)/sizeof(forIN[0]), curPos)) {
1910 const int keyw_len = sizeof(forIN)/sizeof(forIN[0]) + 1;
1911 WINE_TRACE("Found 'IN '\n");
1912 lastWasIn = TRUE;
1913 onlyWhiteSpace = TRUE;
1914 memcpy(&curCopyTo[*curLen], curPos, keyw_len*sizeof(WCHAR));
1915 (*curLen)+=keyw_len;
1916 curPos+=keyw_len;
1917 continue;
1922 /* Nothing 'ends' a REM statement and &&, quotes etc are ineffective,
1923 so just use the default processing ie skip character specific
1924 matching below */
1925 if (!inRem) thisChar = *curPos;
1926 else thisChar = 'X'; /* Character with no special processing */
1928 lastWasWhiteSpace = FALSE; /* Will be reset below */
1930 switch (thisChar) {
1932 case '=': /* drop through - ignore token delimiters at the start of a command */
1933 case ',': /* drop through - ignore token delimiters at the start of a command */
1934 case '\t':/* drop through - ignore token delimiters at the start of a command */
1935 case ' ':
1936 /* If a redirect in place, it ends here */
1937 if (!inQuotes && !lastWasRedirect) {
1939 /* If finishing off a redirect, add a whitespace delimiter */
1940 if (curCopyTo == curRedirs) {
1941 curCopyTo[(*curLen)++] = ' ';
1943 curCopyTo = curString;
1944 curLen = &curStringLen;
1946 if (*curLen > 0) {
1947 curCopyTo[(*curLen)++] = *curPos;
1950 /* Remember just processed whitespace */
1951 lastWasWhiteSpace = TRUE;
1953 break;
1955 case '>': /* drop through - handle redirect chars the same */
1956 case '<':
1957 /* Make a redirect start here */
1958 if (!inQuotes) {
1959 curCopyTo = curRedirs;
1960 curLen = &curRedirsLen;
1961 lastWasRedirect = TRUE;
1964 /* See if 1>, 2> etc, in which case we have some patching up
1965 to do (provided there's a preceding whitespace, and enough
1966 chars read so far) */
1967 if (curStringLen > 2
1968 && (*(curPos-1)>='1') && (*(curPos-1)<='9')
1969 && ((*(curPos-2)==' ') || (*(curPos-2)=='\t'))) {
1970 curStringLen--;
1971 curString[curStringLen] = 0x00;
1972 curCopyTo[(*curLen)++] = *(curPos-1);
1975 curCopyTo[(*curLen)++] = *curPos;
1977 /* If a redirect is immediately followed by '&' (ie. 2>&1) then
1978 do not process that ampersand as an AND operator */
1979 if (thisChar == '>' && *(curPos+1) == '&') {
1980 curCopyTo[(*curLen)++] = *(curPos+1);
1981 curPos++;
1983 break;
1985 case '|': /* Pipe character only if not || */
1986 if (!inQuotes) {
1987 lastWasRedirect = FALSE;
1989 /* Add an entry to the command list */
1990 if (curStringLen > 0) {
1992 /* Add the current command */
1993 WCMD_addCommand(curString, &curStringLen,
1994 curRedirs, &curRedirsLen,
1995 &curCopyTo, &curLen,
1996 prevDelim, curDepth,
1997 &lastEntry, output);
2001 if (*(curPos+1) == '|') {
2002 curPos++; /* Skip other | */
2003 prevDelim = CMD_ONFAILURE;
2004 } else {
2005 prevDelim = CMD_PIPE;
2007 } else {
2008 curCopyTo[(*curLen)++] = *curPos;
2010 break;
2012 case '"': if (WCMD_IsEndQuote(curPos, inQuotes)) {
2013 inQuotes--;
2014 } else {
2015 inQuotes++; /* Quotes within quotes are fun! */
2017 curCopyTo[(*curLen)++] = *curPos;
2018 lastWasRedirect = FALSE;
2019 break;
2021 case '(': /* If a '(' is the first non whitespace in a command portion
2022 ie start of line or just after &&, then we read until an
2023 unquoted ) is found */
2024 WINE_TRACE("Found '(' conditions: curLen(%d), inQ(%d), onlyWS(%d)"
2025 ", for(%d, In:%d, Do:%d)"
2026 ", if(%d, else:%d, lwe:%d)\n",
2027 *curLen, inQuotes,
2028 onlyWhiteSpace,
2029 inFor, lastWasIn, lastWasDo,
2030 inIf, inElse, lastWasElse);
2031 lastWasRedirect = FALSE;
2033 /* Ignore open brackets inside the for set */
2034 if (*curLen == 0 && !inIn) {
2035 curDepth++;
2037 /* If in quotes, ignore brackets */
2038 } else if (inQuotes) {
2039 curCopyTo[(*curLen)++] = *curPos;
2041 /* In a FOR loop, an unquoted '(' may occur straight after
2042 IN or DO
2043 In an IF statement just handle it regardless as we don't
2044 parse the operands
2045 In an ELSE statement, only allow it straight away after
2046 the ELSE and whitespace
2048 } else if (inIf ||
2049 (inElse && lastWasElse && onlyWhiteSpace) ||
2050 (inFor && (lastWasIn || lastWasDo) && onlyWhiteSpace)) {
2052 /* If entering into an 'IN', set inIn */
2053 if (inFor && lastWasIn && onlyWhiteSpace) {
2054 WINE_TRACE("Inside an IN\n");
2055 inIn = TRUE;
2058 /* Add the current command */
2059 WCMD_addCommand(curString, &curStringLen,
2060 curRedirs, &curRedirsLen,
2061 &curCopyTo, &curLen,
2062 prevDelim, curDepth,
2063 &lastEntry, output);
2065 curDepth++;
2066 } else {
2067 curCopyTo[(*curLen)++] = *curPos;
2069 break;
2071 case '&': if (!inQuotes) {
2072 lastWasRedirect = FALSE;
2074 /* Add an entry to the command list */
2075 if (curStringLen > 0) {
2077 /* Add the current command */
2078 WCMD_addCommand(curString, &curStringLen,
2079 curRedirs, &curRedirsLen,
2080 &curCopyTo, &curLen,
2081 prevDelim, curDepth,
2082 &lastEntry, output);
2086 if (*(curPos+1) == '&') {
2087 curPos++; /* Skip other & */
2088 prevDelim = CMD_ONSUCCESS;
2089 } else {
2090 prevDelim = CMD_NONE;
2092 } else {
2093 curCopyTo[(*curLen)++] = *curPos;
2095 break;
2097 case ')': if (!inQuotes && curDepth > 0) {
2098 lastWasRedirect = FALSE;
2100 /* Add the current command if there is one */
2101 if (curStringLen) {
2103 /* Add the current command */
2104 WCMD_addCommand(curString, &curStringLen,
2105 curRedirs, &curRedirsLen,
2106 &curCopyTo, &curLen,
2107 prevDelim, curDepth,
2108 &lastEntry, output);
2111 /* Add an empty entry to the command list */
2112 prevDelim = CMD_NONE;
2113 WCMD_addCommand(NULL, &curStringLen,
2114 curRedirs, &curRedirsLen,
2115 &curCopyTo, &curLen,
2116 prevDelim, curDepth,
2117 &lastEntry, output);
2118 curDepth--;
2120 /* Leave inIn if necessary */
2121 if (inIn) inIn = FALSE;
2122 } else {
2123 curCopyTo[(*curLen)++] = *curPos;
2125 break;
2126 default:
2127 lastWasRedirect = FALSE;
2128 curCopyTo[(*curLen)++] = *curPos;
2131 curPos++;
2133 /* At various times we need to know if we have only skipped whitespace,
2134 so reset this variable and then it will remain true until a non
2135 whitespace is found */
2136 if ((thisChar != ' ') && (thisChar != '\t') && (thisChar != '\n'))
2137 onlyWhiteSpace = FALSE;
2139 /* Flag end of interest in FOR DO and IN parms once something has been processed */
2140 if (!lastWasWhiteSpace) {
2141 lastWasIn = lastWasDo = FALSE;
2144 /* If we have reached the end, add this command into the list */
2145 if (*curPos == 0x00 && *curLen > 0) {
2147 /* Add an entry to the command list */
2148 WCMD_addCommand(curString, &curStringLen,
2149 curRedirs, &curRedirsLen,
2150 &curCopyTo, &curLen,
2151 prevDelim, curDepth,
2152 &lastEntry, output);
2155 /* If we have reached the end of the string, see if bracketing outstanding */
2156 if (*curPos == 0x00 && curDepth > 0 && readFrom != INVALID_HANDLE_VALUE) {
2157 inRem = FALSE;
2158 prevDelim = CMD_NONE;
2159 inQuotes = 0;
2160 memset(extraSpace, 0x00, (MAXSTRING+1) * sizeof(WCHAR));
2162 /* Read more, skipping any blank lines */
2163 while (*extraSpace == 0x00) {
2164 if (!context) WCMD_output_asis( WCMD_LoadMessage(WCMD_MOREPROMPT));
2165 if (!WCMD_fgets(extraSpace, MAXSTRING, readFrom))
2166 break;
2168 curPos = extraSpace;
2169 if (context) handleExpansion(extraSpace, FALSE, NULL, NULL);
2170 /* Continue to echo commands IF echo is on and in batch program */
2171 if (context && echo_mode && extraSpace[0] && (extraSpace[0] != '@')) {
2172 WCMD_output_asis(extraSpace);
2173 WCMD_output_asis(newline);
2178 /* Dump out the parsed output */
2179 WCMD_DumpCommands(*output);
2181 return extraSpace;
2184 /***************************************************************************
2185 * WCMD_process_commands
2187 * Process all the commands read in so far
2189 CMD_LIST *WCMD_process_commands(CMD_LIST *thisCmd, BOOL oneBracket,
2190 const WCHAR *var, const WCHAR *val) {
2192 int bdepth = -1;
2194 if (thisCmd && oneBracket) bdepth = thisCmd->bracketDepth;
2196 /* Loop through the commands, processing them one by one */
2197 while (thisCmd) {
2199 CMD_LIST *origCmd = thisCmd;
2201 /* If processing one bracket only, and we find the end bracket
2202 entry (or less), return */
2203 if (oneBracket && !thisCmd->command &&
2204 bdepth <= thisCmd->bracketDepth) {
2205 WINE_TRACE("Finished bracket @ %p, next command is %p\n",
2206 thisCmd, thisCmd->nextcommand);
2207 return thisCmd->nextcommand;
2210 /* Ignore the NULL entries a ')' inserts (Only 'if' cares
2211 about them and it will be handled in there)
2212 Also, skip over any batch labels (eg. :fred) */
2213 if (thisCmd->command && thisCmd->command[0] != ':') {
2214 WINE_TRACE("Executing command: '%s'\n", wine_dbgstr_w(thisCmd->command));
2215 WCMD_execute (thisCmd->command, thisCmd->redirects, var, val, &thisCmd);
2218 /* Step on unless the command itself already stepped on */
2219 if (thisCmd == origCmd) thisCmd = thisCmd->nextcommand;
2221 return NULL;
2224 /***************************************************************************
2225 * WCMD_free_commands
2227 * Frees the storage held for a parsed command line
2228 * - This is not done in the process_commands, as eventually the current
2229 * pointer will be modified within the commands, and hence a single free
2230 * routine is simpler
2232 void WCMD_free_commands(CMD_LIST *cmds) {
2234 /* Loop through the commands, freeing them one by one */
2235 while (cmds) {
2236 CMD_LIST *thisCmd = cmds;
2237 cmds = cmds->nextcommand;
2238 HeapFree(GetProcessHeap(), 0, thisCmd->command);
2239 HeapFree(GetProcessHeap(), 0, thisCmd->redirects);
2240 HeapFree(GetProcessHeap(), 0, thisCmd);
2245 /*****************************************************************************
2246 * Main entry point. This is a console application so we have a main() not a
2247 * winmain().
2250 int wmain (int argc, WCHAR *argvW[])
2252 int args;
2253 WCHAR *cmd;
2254 WCHAR string[1024];
2255 WCHAR envvar[4];
2256 BOOL opt_q;
2257 int opt_t = 0;
2258 static const WCHAR promptW[] = {'P','R','O','M','P','T','\0'};
2259 static const WCHAR defaultpromptW[] = {'$','P','$','G','\0'};
2260 CMD_LIST *toExecute = NULL; /* Commands left to be executed */
2262 srand(time(NULL));
2264 /* Pre initialize some messages */
2265 strcpyW(anykey, WCMD_LoadMessage(WCMD_ANYKEY));
2266 cmd = WCMD_format_string(WCMD_LoadMessage(WCMD_VERSION), PACKAGE_VERSION);
2267 strcpyW(version_string, cmd);
2268 LocalFree(cmd);
2269 cmd = NULL;
2271 args = argc;
2272 opt_c = opt_k = opt_q = opt_s = FALSE;
2273 while (args > 0)
2275 WCHAR c;
2276 WINE_TRACE("Command line parm: '%s'\n", wine_dbgstr_w(*argvW));
2277 if ((*argvW)[0]!='/' || (*argvW)[1]=='\0') {
2278 argvW++;
2279 args--;
2280 continue;
2283 c=(*argvW)[1];
2284 if (tolowerW(c)=='c') {
2285 opt_c = TRUE;
2286 } else if (tolowerW(c)=='q') {
2287 opt_q = TRUE;
2288 } else if (tolowerW(c)=='k') {
2289 opt_k = TRUE;
2290 } else if (tolowerW(c)=='s') {
2291 opt_s = TRUE;
2292 } else if (tolowerW(c)=='a') {
2293 unicodeOutput = FALSE;
2294 } else if (tolowerW(c)=='u') {
2295 unicodeOutput = TRUE;
2296 } else if (tolowerW(c)=='t' && (*argvW)[2]==':') {
2297 opt_t=strtoulW(&(*argvW)[3], NULL, 16);
2298 } else if (tolowerW(c)=='x' || tolowerW(c)=='y') {
2299 /* Ignored for compatibility with Windows */
2302 if ((*argvW)[2]==0) {
2303 argvW++;
2304 args--;
2306 else /* handle `cmd /cnotepad.exe` and `cmd /x/c ...` */
2308 *argvW+=2;
2311 if (opt_c || opt_k) /* break out of parsing immediately after c or k */
2312 break;
2315 if (opt_q) {
2316 static const WCHAR eoff[] = {'O','F','F','\0'};
2317 WCMD_echo(eoff);
2320 if (opt_c || opt_k) {
2321 int len,qcount;
2322 WCHAR** arg;
2323 int argsLeft;
2324 WCHAR* p;
2326 /* opt_s left unflagged if the command starts with and contains exactly
2327 * one quoted string (exactly two quote characters). The quoted string
2328 * must be an executable name that has whitespace and must not have the
2329 * following characters: &<>()@^| */
2331 /* Build the command to execute */
2332 len = 0;
2333 qcount = 0;
2334 argsLeft = args;
2335 for (arg = argvW; argsLeft>0; arg++,argsLeft--)
2337 int has_space,bcount;
2338 WCHAR* a;
2340 has_space=0;
2341 bcount=0;
2342 a=*arg;
2343 if( !*a ) has_space=1;
2344 while (*a!='\0') {
2345 if (*a=='\\') {
2346 bcount++;
2347 } else {
2348 if (*a==' ' || *a=='\t') {
2349 has_space=1;
2350 } else if (*a=='"') {
2351 /* doubling of '\' preceding a '"',
2352 * plus escaping of said '"'
2354 len+=2*bcount+1;
2355 qcount++;
2357 bcount=0;
2359 a++;
2361 len+=(a-*arg) + 1; /* for the separating space */
2362 if (has_space)
2364 len+=2; /* for the quotes */
2365 qcount+=2;
2369 if (qcount!=2)
2370 opt_s = TRUE;
2372 /* check argvW[0] for a space and invalid characters */
2373 if (!opt_s) {
2374 opt_s = TRUE;
2375 p=*argvW;
2376 while (*p!='\0') {
2377 if (*p=='&' || *p=='<' || *p=='>' || *p=='(' || *p==')'
2378 || *p=='@' || *p=='^' || *p=='|') {
2379 opt_s = TRUE;
2380 break;
2382 if (*p==' ')
2383 opt_s = FALSE;
2384 p++;
2388 cmd = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
2389 if (!cmd)
2390 exit(1);
2392 p = cmd;
2393 argsLeft = args;
2394 for (arg = argvW; argsLeft>0; arg++,argsLeft--)
2396 int has_space,has_quote;
2397 WCHAR* a;
2399 /* Check for quotes and spaces in this argument */
2400 has_space=has_quote=0;
2401 a=*arg;
2402 if( !*a ) has_space=1;
2403 while (*a!='\0') {
2404 if (*a==' ' || *a=='\t') {
2405 has_space=1;
2406 if (has_quote)
2407 break;
2408 } else if (*a=='"') {
2409 has_quote=1;
2410 if (has_space)
2411 break;
2413 a++;
2416 /* Now transfer it to the command line */
2417 if (has_space)
2418 *p++='"';
2419 if (has_quote) {
2420 int bcount;
2421 WCHAR* a;
2423 bcount=0;
2424 a=*arg;
2425 while (*a!='\0') {
2426 if (*a=='\\') {
2427 *p++=*a;
2428 bcount++;
2429 } else {
2430 if (*a=='"') {
2431 int i;
2433 /* Double all the '\\' preceding this '"', plus one */
2434 for (i=0;i<=bcount;i++)
2435 *p++='\\';
2436 *p++='"';
2437 } else {
2438 *p++=*a;
2440 bcount=0;
2442 a++;
2444 } else {
2445 strcpyW(p,*arg);
2446 p+=strlenW(*arg);
2448 if (has_space)
2449 *p++='"';
2450 *p++=' ';
2452 if (p > cmd)
2453 p--; /* remove last space */
2454 *p = '\0';
2456 WINE_TRACE("/c command line: '%s'\n", wine_dbgstr_w(cmd));
2458 /* strip first and last quote characters if opt_s; check for invalid
2459 * executable is done later */
2460 if (opt_s && *cmd=='\"')
2461 WCMD_strip_quotes(cmd);
2464 if (opt_c) {
2465 /* If we do a "cmd /c command", we don't want to allocate a new
2466 * console since the command returns immediately. Rather, we use
2467 * the currently allocated input and output handles. This allows
2468 * us to pipe to and read from the command interpreter.
2471 /* Parse the command string, without reading any more input */
2472 WCMD_ReadAndParseLine(cmd, &toExecute, INVALID_HANDLE_VALUE);
2473 WCMD_process_commands(toExecute, FALSE, NULL, NULL);
2474 WCMD_free_commands(toExecute);
2475 toExecute = NULL;
2477 HeapFree(GetProcessHeap(), 0, cmd);
2478 return errorlevel;
2481 SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), ENABLE_LINE_INPUT |
2482 ENABLE_ECHO_INPUT | ENABLE_PROCESSED_INPUT);
2483 SetConsoleTitleW(WCMD_LoadMessage(WCMD_CONSTITLE));
2485 /* Note: cmd.exe /c dir does not get a new color, /k dir does */
2486 if (opt_t) {
2487 if (!(((opt_t & 0xF0) >> 4) == (opt_t & 0x0F))) {
2488 defaultColor = opt_t & 0xFF;
2489 param1[0] = 0x00;
2490 WCMD_color();
2492 } else {
2493 /* Check HKCU\Software\Microsoft\Command Processor
2494 Then HKLM\Software\Microsoft\Command Processor
2495 for defaultcolour value
2496 Note Can be supplied as DWORD or REG_SZ
2497 Note2 When supplied as REG_SZ it's in decimal!!! */
2498 HKEY key;
2499 DWORD type;
2500 DWORD value=0, size=4;
2501 static const WCHAR regKeyW[] = {'S','o','f','t','w','a','r','e','\\',
2502 'M','i','c','r','o','s','o','f','t','\\',
2503 'C','o','m','m','a','n','d',' ','P','r','o','c','e','s','s','o','r','\0'};
2504 static const WCHAR dfltColorW[] = {'D','e','f','a','u','l','t','C','o','l','o','r','\0'};
2506 if (RegOpenKeyExW(HKEY_CURRENT_USER, regKeyW,
2507 0, KEY_READ, &key) == ERROR_SUCCESS) {
2508 WCHAR strvalue[4];
2510 /* See if DWORD or REG_SZ */
2511 if (RegQueryValueExW(key, dfltColorW, NULL, &type,
2512 NULL, NULL) == ERROR_SUCCESS) {
2513 if (type == REG_DWORD) {
2514 size = sizeof(DWORD);
2515 RegQueryValueExW(key, dfltColorW, NULL, NULL,
2516 (LPBYTE)&value, &size);
2517 } else if (type == REG_SZ) {
2518 size = sizeof(strvalue)/sizeof(WCHAR);
2519 RegQueryValueExW(key, dfltColorW, NULL, NULL,
2520 (LPBYTE)strvalue, &size);
2521 value = strtoulW(strvalue, NULL, 10);
2524 RegCloseKey(key);
2527 if (value == 0 && RegOpenKeyExW(HKEY_LOCAL_MACHINE, regKeyW,
2528 0, KEY_READ, &key) == ERROR_SUCCESS) {
2529 WCHAR strvalue[4];
2531 /* See if DWORD or REG_SZ */
2532 if (RegQueryValueExW(key, dfltColorW, NULL, &type,
2533 NULL, NULL) == ERROR_SUCCESS) {
2534 if (type == REG_DWORD) {
2535 size = sizeof(DWORD);
2536 RegQueryValueExW(key, dfltColorW, NULL, NULL,
2537 (LPBYTE)&value, &size);
2538 } else if (type == REG_SZ) {
2539 size = sizeof(strvalue)/sizeof(WCHAR);
2540 RegQueryValueExW(key, dfltColorW, NULL, NULL,
2541 (LPBYTE)strvalue, &size);
2542 value = strtoulW(strvalue, NULL, 10);
2545 RegCloseKey(key);
2548 /* If one found, set the screen to that colour */
2549 if (!(((value & 0xF0) >> 4) == (value & 0x0F))) {
2550 defaultColor = value & 0xFF;
2551 param1[0] = 0x00;
2552 WCMD_color();
2557 /* Save cwd into appropriate env var */
2558 GetCurrentDirectoryW(1024, string);
2559 if (IsCharAlphaW(string[0]) && string[1] == ':') {
2560 static const WCHAR fmt[] = {'=','%','c',':','\0'};
2561 wsprintfW(envvar, fmt, string[0]);
2562 SetEnvironmentVariableW(envvar, string);
2563 WINE_TRACE("Set %s to %s\n", wine_dbgstr_w(envvar), wine_dbgstr_w(string));
2566 if (opt_k) {
2567 /* Parse the command string, without reading any more input */
2568 WCMD_ReadAndParseLine(cmd, &toExecute, INVALID_HANDLE_VALUE);
2569 WCMD_process_commands(toExecute, FALSE, NULL, NULL);
2570 WCMD_free_commands(toExecute);
2571 toExecute = NULL;
2572 HeapFree(GetProcessHeap(), 0, cmd);
2576 * Loop forever getting commands and executing them.
2579 SetEnvironmentVariableW(promptW, defaultpromptW);
2580 WCMD_version ();
2581 while (TRUE) {
2583 /* Read until EOF (which for std input is never, but if redirect
2584 in place, may occur */
2585 if (echo_mode) WCMD_show_prompt();
2586 if (!WCMD_ReadAndParseLine(NULL, &toExecute, GetStdHandle(STD_INPUT_HANDLE)))
2587 break;
2588 WCMD_process_commands(toExecute, FALSE, NULL, NULL);
2589 WCMD_free_commands(toExecute);
2590 toExecute = NULL;
2592 return 0;