cmd: Improve handle type recognition in WCMD_ReadFile.
[wine/multimedia.git] / programs / cmd / wcmdmain.c
blob5611642deb43f46e1c0ab3060fb44212229de526
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 const WCHAR inbuilt[][10] = {
35 {'C','A','L','L','\0'},
36 {'C','D','\0'},
37 {'C','H','D','I','R','\0'},
38 {'C','L','S','\0'},
39 {'C','O','P','Y','\0'},
40 {'C','T','T','Y','\0'},
41 {'D','A','T','E','\0'},
42 {'D','E','L','\0'},
43 {'D','I','R','\0'},
44 {'E','C','H','O','\0'},
45 {'E','R','A','S','E','\0'},
46 {'F','O','R','\0'},
47 {'G','O','T','O','\0'},
48 {'H','E','L','P','\0'},
49 {'I','F','\0'},
50 {'L','A','B','E','L','\0'},
51 {'M','D','\0'},
52 {'M','K','D','I','R','\0'},
53 {'M','O','V','E','\0'},
54 {'P','A','T','H','\0'},
55 {'P','A','U','S','E','\0'},
56 {'P','R','O','M','P','T','\0'},
57 {'R','E','M','\0'},
58 {'R','E','N','\0'},
59 {'R','E','N','A','M','E','\0'},
60 {'R','D','\0'},
61 {'R','M','D','I','R','\0'},
62 {'S','E','T','\0'},
63 {'S','H','I','F','T','\0'},
64 {'T','I','M','E','\0'},
65 {'T','I','T','L','E','\0'},
66 {'T','Y','P','E','\0'},
67 {'V','E','R','I','F','Y','\0'},
68 {'V','E','R','\0'},
69 {'V','O','L','\0'},
70 {'E','N','D','L','O','C','A','L','\0'},
71 {'S','E','T','L','O','C','A','L','\0'},
72 {'P','U','S','H','D','\0'},
73 {'P','O','P','D','\0'},
74 {'A','S','S','O','C','\0'},
75 {'C','O','L','O','R','\0'},
76 {'F','T','Y','P','E','\0'},
77 {'M','O','R','E','\0'},
78 {'C','H','O','I','C','E','\0'},
79 {'E','X','I','T','\0'}
82 const WCHAR externals[NUM_EXTERNALS][10] = {
83 {'A','T','T','R','I','B','\0'},
84 {'X','C','O','P','Y','\0'}
87 HINSTANCE hinst;
88 DWORD errorlevel;
89 int defaultColor = 7;
90 BOOL echo_mode = TRUE;
91 static int opt_c, opt_k, opt_s;
92 const WCHAR newline[] = {'\r','\n','\0'};
93 static const WCHAR equalsW[] = {'=','\0'};
94 static const WCHAR closeBW[] = {')','\0'};
95 WCHAR anykey[100];
96 WCHAR version_string[100];
97 WCHAR quals[MAX_PATH], param1[MAXSTRING], param2[MAXSTRING];
98 BATCH_CONTEXT *context = NULL;
99 extern struct env_stack *pushd_directories;
100 static const WCHAR *pagedMessage = NULL;
101 static char *output_bufA = NULL;
102 #define MAX_WRITECONSOLE_SIZE 65535
103 static BOOL unicodePipes = FALSE;
106 * Returns a buffer for reading from/writing to file
107 * Never freed
109 static char *get_file_buffer(void)
111 if (!output_bufA) {
112 output_bufA = HeapAlloc(GetProcessHeap(), 0, MAX_WRITECONSOLE_SIZE);
113 if (!output_bufA)
114 WINE_FIXME("Out of memory - could not allocate ansi 64K buffer\n");
116 return output_bufA;
119 /*******************************************************************
120 * WCMD_output_asis_len - send output to current standard output
122 * Output a formatted unicode string. Ideally this will go to the console
123 * and hence required WriteConsoleW to output it, however if file i/o is
124 * redirected, it needs to be WriteFile'd using OEM (not ANSI) format
126 static void WCMD_output_asis_len(const WCHAR *message, int len, HANDLE device) {
128 DWORD nOut= 0;
129 DWORD res = 0;
131 /* If nothing to write, return (MORE does this sometimes) */
132 if (!len) return;
134 /* Try to write as unicode assuming it is to a console */
135 res = WriteConsoleW(device, message, len, &nOut, NULL);
137 /* If writing to console fails, assume its file
138 i/o so convert to OEM codepage and output */
139 if (!res) {
140 BOOL usedDefaultChar = FALSE;
141 DWORD convertedChars;
142 char *buffer;
144 if (!unicodePipes) {
146 if (!(buffer = get_file_buffer()))
147 return;
149 /* Convert to OEM, then output */
150 convertedChars = WideCharToMultiByte(GetConsoleOutputCP(), 0, message,
151 len, buffer, MAX_WRITECONSOLE_SIZE,
152 "?", &usedDefaultChar);
153 WriteFile(device, buffer, convertedChars,
154 &nOut, FALSE);
155 } else {
156 WriteFile(device, message, len*sizeof(WCHAR),
157 &nOut, FALSE);
160 return;
163 /*******************************************************************
164 * WCMD_output - send output to current standard output device.
168 void WCMD_output (const WCHAR *format, ...) {
170 va_list ap;
171 WCHAR string[1024];
172 int ret;
174 va_start(ap,format);
175 ret = vsnprintfW(string, sizeof(string)/sizeof(WCHAR), format, ap);
176 if( ret >= (sizeof(string)/sizeof(WCHAR))) {
177 WINE_ERR("Output truncated\n" );
178 ret = (sizeof(string)/sizeof(WCHAR)) - 1;
179 string[ret] = '\0';
181 va_end(ap);
182 WCMD_output_asis_len(string, ret, GetStdHandle(STD_OUTPUT_HANDLE));
185 /*******************************************************************
186 * WCMD_output_stderr - send output to current standard error device.
190 void WCMD_output_stderr (const WCHAR *format, ...) {
192 va_list ap;
193 WCHAR string[1024];
194 int ret;
196 va_start(ap,format);
197 ret = vsnprintfW(string, sizeof(string)/sizeof(WCHAR), format, ap);
198 if( ret >= (sizeof(string)/sizeof(WCHAR))) {
199 WINE_ERR("Output truncated\n" );
200 ret = (sizeof(string)/sizeof(WCHAR)) - 1;
201 string[ret] = '\0';
203 va_end(ap);
204 WCMD_output_asis_len(string, ret, GetStdHandle(STD_ERROR_HANDLE));
207 static int line_count;
208 static int max_height;
209 static int max_width;
210 static BOOL paged_mode;
211 static int numChars;
213 void WCMD_enter_paged_mode(const WCHAR *msg)
215 CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
217 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &consoleInfo)) {
218 max_height = consoleInfo.dwSize.Y;
219 max_width = consoleInfo.dwSize.X;
220 } else {
221 max_height = 25;
222 max_width = 80;
224 paged_mode = TRUE;
225 line_count = 0;
226 numChars = 0;
227 pagedMessage = (msg==NULL)? anykey : msg;
230 void WCMD_leave_paged_mode(void)
232 paged_mode = FALSE;
233 pagedMessage = NULL;
236 static inline BOOL is_console_handle(HANDLE h)
238 return (((DWORD_PTR)h) & 3) == 3;
241 /***************************************************************************
242 * WCMD_Readfile
244 * Read characters in from a console/file, returning result in Unicode
246 BOOL WCMD_ReadFile(const HANDLE hIn, WCHAR *intoBuf, const DWORD maxChars, LPDWORD charsRead)
248 DWORD numRead;
249 char *buffer;
251 if (is_console_handle(hIn))
252 /* Try to read from console as Unicode */
253 return ReadConsoleW(hIn, intoBuf, maxChars, charsRead, NULL);
255 /* We assume it's a file handle and read then convert from assumed OEM codepage */
256 if (!(buffer = get_file_buffer()))
257 return FALSE;
259 if (!ReadFile(hIn, buffer, maxChars, &numRead, NULL))
260 return FALSE;
262 *charsRead = MultiByteToWideChar(GetConsoleCP(), 0, buffer, numRead, intoBuf, maxChars);
264 return TRUE;
267 /*******************************************************************
268 * WCMD_output_asis_handle
270 * Send output to specified handle without formatting e.g. when message contains '%'
272 static void WCMD_output_asis_handle (DWORD std_handle, const WCHAR *message) {
273 DWORD count;
274 const WCHAR* ptr;
275 WCHAR string[1024];
276 HANDLE handle = GetStdHandle(std_handle);
278 if (paged_mode) {
279 do {
280 ptr = message;
281 while (*ptr && *ptr!='\n' && (numChars < max_width)) {
282 numChars++;
283 ptr++;
285 if (*ptr == '\n') ptr++;
286 WCMD_output_asis_len(message, (ptr) ? ptr - message : strlenW(message), handle);
287 if (ptr) {
288 numChars = 0;
289 if (++line_count >= max_height - 1) {
290 line_count = 0;
291 WCMD_output_asis_len(pagedMessage, strlenW(pagedMessage), handle);
292 WCMD_ReadFile(GetStdHandle(STD_INPUT_HANDLE), string, sizeof(string)/sizeof(WCHAR), &count);
295 } while (((message = ptr) != NULL) && (*ptr));
296 } else {
297 WCMD_output_asis_len(message, lstrlenW(message), handle);
301 /*******************************************************************
302 * WCMD_output_asis
304 * Send output to current standard output device, without formatting
305 * e.g. when message contains '%'
307 void WCMD_output_asis (const WCHAR *message) {
308 WCMD_output_asis_handle(STD_OUTPUT_HANDLE, message);
311 /*******************************************************************
312 * WCMD_output_asis_stderr
314 * Send output to current standard error device, without formatting
315 * e.g. when message contains '%'
317 void WCMD_output_asis_stderr (const WCHAR *message) {
318 WCMD_output_asis_handle(STD_ERROR_HANDLE, message);
321 /****************************************************************************
322 * WCMD_print_error
324 * Print the message for GetLastError
327 void WCMD_print_error (void) {
328 LPVOID lpMsgBuf;
329 DWORD error_code;
330 int status;
332 error_code = GetLastError ();
333 status = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
334 NULL, error_code, 0, (LPWSTR) &lpMsgBuf, 0, NULL);
335 if (!status) {
336 WINE_FIXME ("Cannot display message for error %d, status %d\n",
337 error_code, GetLastError());
338 return;
341 WCMD_output_asis_len(lpMsgBuf, lstrlenW(lpMsgBuf),
342 GetStdHandle(STD_ERROR_HANDLE));
343 LocalFree (lpMsgBuf);
344 WCMD_output_asis_len (newline, lstrlenW(newline),
345 GetStdHandle(STD_ERROR_HANDLE));
346 return;
349 /******************************************************************************
350 * WCMD_show_prompt
352 * Display the prompt on STDout
356 static void WCMD_show_prompt (void) {
358 int status;
359 WCHAR out_string[MAX_PATH], curdir[MAX_PATH], prompt_string[MAX_PATH];
360 WCHAR *p, *q;
361 DWORD len;
362 static const WCHAR envPrompt[] = {'P','R','O','M','P','T','\0'};
364 len = GetEnvironmentVariableW(envPrompt, prompt_string,
365 sizeof(prompt_string)/sizeof(WCHAR));
366 if ((len == 0) || (len >= (sizeof(prompt_string)/sizeof(WCHAR)))) {
367 static const WCHAR dfltPrompt[] = {'$','P','$','G','\0'};
368 strcpyW (prompt_string, dfltPrompt);
370 p = prompt_string;
371 q = out_string;
372 *q++ = '\r';
373 *q++ = '\n';
374 *q = '\0';
375 while (*p != '\0') {
376 if (*p != '$') {
377 *q++ = *p++;
378 *q = '\0';
380 else {
381 p++;
382 switch (toupper(*p)) {
383 case '$':
384 *q++ = '$';
385 break;
386 case 'A':
387 *q++ = '&';
388 break;
389 case 'B':
390 *q++ = '|';
391 break;
392 case 'C':
393 *q++ = '(';
394 break;
395 case 'D':
396 GetDateFormatW(LOCALE_USER_DEFAULT, DATE_SHORTDATE, NULL, NULL, q, MAX_PATH);
397 while (*q) q++;
398 break;
399 case 'E':
400 *q++ = '\E';
401 break;
402 case 'F':
403 *q++ = ')';
404 break;
405 case 'G':
406 *q++ = '>';
407 break;
408 case 'H':
409 *q++ = '\b';
410 break;
411 case 'L':
412 *q++ = '<';
413 break;
414 case 'N':
415 status = GetCurrentDirectoryW(sizeof(curdir)/sizeof(WCHAR), curdir);
416 if (status) {
417 *q++ = curdir[0];
419 break;
420 case 'P':
421 status = GetCurrentDirectoryW(sizeof(curdir)/sizeof(WCHAR), curdir);
422 if (status) {
423 strcatW (q, curdir);
424 while (*q) q++;
426 break;
427 case 'Q':
428 *q++ = '=';
429 break;
430 case 'S':
431 *q++ = ' ';
432 break;
433 case 'T':
434 GetTimeFormatW(LOCALE_USER_DEFAULT, 0, NULL, NULL, q, MAX_PATH);
435 while (*q) q++;
436 break;
437 case 'V':
438 strcatW (q, version_string);
439 while (*q) q++;
440 break;
441 case '_':
442 *q++ = '\n';
443 break;
444 case '+':
445 if (pushd_directories) {
446 memset(q, '+', pushd_directories->u.stackdepth);
447 q = q + pushd_directories->u.stackdepth;
449 break;
451 p++;
452 *q = '\0';
455 WCMD_output_asis (out_string);
459 /*************************************************************************
460 * WCMD_strdupW
461 * A wide version of strdup as its missing from unicode.h
463 WCHAR *WCMD_strdupW(const WCHAR *input) {
464 int len=strlenW(input)+1;
465 WCHAR *result = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
466 memcpy(result, input, len * sizeof(WCHAR));
467 return result;
470 /*************************************************************************
471 * WCMD_strsubstW
472 * Replaces a portion of a Unicode string with the specified string.
473 * It's up to the caller to ensure there is enough space in the
474 * destination buffer.
476 void WCMD_strsubstW(WCHAR *start, const WCHAR *next, const WCHAR *insert, int len) {
478 if (len < 0)
479 len=insert ? lstrlenW(insert) : 0;
480 if (start+len != next)
481 memmove(start+len, next, (strlenW(next) + 1) * sizeof(*next));
482 if (insert)
483 memcpy(start, insert, len * sizeof(*insert));
486 /***************************************************************************
487 * WCMD_skip_leading_spaces
489 * Return a pointer to the first non-whitespace character of string.
490 * Does not modify the input string.
492 WCHAR *WCMD_skip_leading_spaces (WCHAR *string) {
494 WCHAR *ptr;
496 ptr = string;
497 while (*ptr == ' ' || *ptr == '\t') ptr++;
498 return ptr;
501 /***************************************************************************
502 * WCMD_keyword_ws_found
504 * Checks if the string located at ptr matches a keyword (of length len)
505 * followed by a whitespace character (space or tab)
507 BOOL WCMD_keyword_ws_found(const WCHAR *keyword, int len, const WCHAR *ptr) {
508 return (CompareStringW(LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
509 ptr, len, keyword, len) == CSTR_EQUAL)
510 && ((*(ptr + len) == ' ') || (*(ptr + len) == '\t'));
513 /*************************************************************************
514 * WCMD_opt_s_strip_quotes
516 * Remove first and last quote WCHARacters, preserving all other text
518 void WCMD_opt_s_strip_quotes(WCHAR *cmd) {
519 WCHAR *src = cmd + 1, *dest = cmd, *lastq = NULL;
520 while((*dest=*src) != '\0') {
521 if (*src=='\"')
522 lastq=dest;
523 dest++, src++;
525 if (lastq) {
526 dest=lastq++;
527 while ((*dest++=*lastq++) != 0)
533 /*************************************************************************
534 * WCMD_is_magic_envvar
535 * Return TRUE if s is '%'magicvar'%'
536 * and is not masked by a real environment variable.
539 static inline BOOL WCMD_is_magic_envvar(const WCHAR *s, const WCHAR *magicvar)
541 int len;
543 if (s[0] != '%')
544 return FALSE; /* Didn't begin with % */
545 len = strlenW(s);
546 if (len < 2 || s[len-1] != '%')
547 return FALSE; /* Didn't end with another % */
549 if (CompareStringW(LOCALE_USER_DEFAULT,
550 NORM_IGNORECASE | SORT_STRINGSORT,
551 s+1, len-2, magicvar, -1) != CSTR_EQUAL) {
552 /* Name doesn't match. */
553 return FALSE;
556 if (GetEnvironmentVariableW(magicvar, NULL, 0) > 0) {
557 /* Masked by real environment variable. */
558 return FALSE;
561 return TRUE;
564 /*************************************************************************
565 * WCMD_expand_envvar
567 * Expands environment variables, allowing for WCHARacter substitution
569 static WCHAR *WCMD_expand_envvar(WCHAR *start,
570 const WCHAR *forVar, const WCHAR *forVal) {
571 WCHAR *endOfVar = NULL, *s;
572 WCHAR *colonpos = NULL;
573 WCHAR thisVar[MAXSTRING];
574 WCHAR thisVarContents[MAXSTRING];
575 WCHAR savedchar = 0x00;
576 int len;
578 static const WCHAR ErrorLvl[] = {'E','R','R','O','R','L','E','V','E','L','\0'};
579 static const WCHAR Date[] = {'D','A','T','E','\0'};
580 static const WCHAR Time[] = {'T','I','M','E','\0'};
581 static const WCHAR Cd[] = {'C','D','\0'};
582 static const WCHAR Random[] = {'R','A','N','D','O','M','\0'};
583 static const WCHAR Delims[] = {'%',' ',':','\0'};
585 WINE_TRACE("Expanding: %s (%s,%s)\n", wine_dbgstr_w(start),
586 wine_dbgstr_w(forVal), wine_dbgstr_w(forVar));
588 /* Find the end of the environment variable, and extract name */
589 endOfVar = strpbrkW(start+1, Delims);
591 if (endOfVar == NULL || *endOfVar==' ') {
593 /* In batch program, missing terminator for % and no following
594 ':' just removes the '%' */
595 if (context) {
596 WCMD_strsubstW(start, start + 1, NULL, 0);
597 return start;
598 } else {
600 /* In command processing, just ignore it - allows command line
601 syntax like: for %i in (a.a) do echo %i */
602 return start+1;
606 /* If ':' found, process remaining up until '%' (or stop at ':' if
607 a missing '%' */
608 if (*endOfVar==':') {
609 WCHAR *endOfVar2 = strchrW(endOfVar+1, '%');
610 if (endOfVar2 != NULL) endOfVar = endOfVar2;
613 memcpy(thisVar, start, ((endOfVar - start) + 1) * sizeof(WCHAR));
614 thisVar[(endOfVar - start)+1] = 0x00;
615 colonpos = strchrW(thisVar+1, ':');
617 /* If there's complex substitution, just need %var% for now
618 to get the expanded data to play with */
619 if (colonpos) {
620 *colonpos = '%';
621 savedchar = *(colonpos+1);
622 *(colonpos+1) = 0x00;
625 WINE_TRACE("Retrieving contents of %s\n", wine_dbgstr_w(thisVar));
627 /* Expand to contents, if unchanged, return */
628 /* Handle DATE, TIME, ERRORLEVEL and CD replacements allowing */
629 /* override if existing env var called that name */
630 if (WCMD_is_magic_envvar(thisVar, ErrorLvl)) {
631 static const WCHAR fmt[] = {'%','d','\0'};
632 wsprintfW(thisVarContents, fmt, errorlevel);
633 len = strlenW(thisVarContents);
634 } else if (WCMD_is_magic_envvar(thisVar, Date)) {
635 GetDateFormatW(LOCALE_USER_DEFAULT, DATE_SHORTDATE, NULL,
636 NULL, thisVarContents, MAXSTRING);
637 len = strlenW(thisVarContents);
638 } else if (WCMD_is_magic_envvar(thisVar, Time)) {
639 GetTimeFormatW(LOCALE_USER_DEFAULT, TIME_NOSECONDS, NULL,
640 NULL, thisVarContents, MAXSTRING);
641 len = strlenW(thisVarContents);
642 } else if (WCMD_is_magic_envvar(thisVar, Cd)) {
643 GetCurrentDirectoryW(MAXSTRING, thisVarContents);
644 len = strlenW(thisVarContents);
645 } else if (WCMD_is_magic_envvar(thisVar, Random)) {
646 static const WCHAR fmt[] = {'%','d','\0'};
647 wsprintfW(thisVarContents, fmt, rand() % 32768);
648 len = strlenW(thisVarContents);
650 /* Look for a matching 'for' variable */
651 } else if (forVar &&
652 (CompareStringW(LOCALE_USER_DEFAULT,
653 SORT_STRINGSORT,
654 thisVar,
655 (colonpos - thisVar) - 1,
656 forVar, -1) == CSTR_EQUAL)) {
657 strcpyW(thisVarContents, forVal);
658 len = strlenW(thisVarContents);
660 } else {
662 len = ExpandEnvironmentStringsW(thisVar, thisVarContents,
663 sizeof(thisVarContents)/sizeof(WCHAR));
666 if (len == 0)
667 return endOfVar+1;
669 /* In a batch program, unknown env vars are replaced with nothing,
670 note syntax %garbage:1,3% results in anything after the ':'
671 except the %
672 From the command line, you just get back what you entered */
673 if (lstrcmpiW(thisVar, thisVarContents) == 0) {
675 /* Restore the complex part after the compare */
676 if (colonpos) {
677 *colonpos = ':';
678 *(colonpos+1) = savedchar;
681 /* Command line - just ignore this */
682 if (context == NULL) return endOfVar+1;
685 /* Batch - replace unknown env var with nothing */
686 if (colonpos == NULL) {
687 WCMD_strsubstW(start, endOfVar + 1, NULL, 0);
688 } else {
689 len = strlenW(thisVar);
690 thisVar[len-1] = 0x00;
691 /* If %:...% supplied, : is retained */
692 if (colonpos == thisVar+1) {
693 WCMD_strsubstW(start, endOfVar + 1, colonpos, -1);
694 } else {
695 WCMD_strsubstW(start, endOfVar + 1, colonpos + 1, -1);
698 return start;
702 /* See if we need to do complex substitution (any ':'s), if not
703 then our work here is done */
704 if (colonpos == NULL) {
705 WCMD_strsubstW(start, endOfVar + 1, thisVarContents, -1);
706 return start;
709 /* Restore complex bit */
710 *colonpos = ':';
711 *(colonpos+1) = savedchar;
714 Handle complex substitutions:
715 xxx=yyy (replace xxx with yyy)
716 *xxx=yyy (replace up to and including xxx with yyy)
717 ~x (from x WCHARs in)
718 ~-x (from x WCHARs from the end)
719 ~x,y (from x WCHARs in for y WCHARacters)
720 ~x,-y (from x WCHARs in until y WCHARacters from the end)
723 /* ~ is substring manipulation */
724 if (savedchar == '~') {
726 int substrposition, substrlength = 0;
727 WCHAR *commapos = strchrW(colonpos+2, ',');
728 WCHAR *startCopy;
730 substrposition = atolW(colonpos+2);
731 if (commapos) substrlength = atolW(commapos+1);
733 /* Check bounds */
734 if (substrposition >= 0) {
735 startCopy = &thisVarContents[min(substrposition, len)];
736 } else {
737 startCopy = &thisVarContents[max(0, len+substrposition-1)];
740 if (commapos == NULL) {
741 /* Copy the lot */
742 WCMD_strsubstW(start, endOfVar + 1, startCopy, -1);
743 } else if (substrlength < 0) {
745 int copybytes = (len+substrlength-1)-(startCopy-thisVarContents);
746 if (copybytes > len) copybytes = len;
747 else if (copybytes < 0) copybytes = 0;
748 WCMD_strsubstW(start, endOfVar + 1, startCopy, copybytes);
749 } else {
750 WCMD_strsubstW(start, endOfVar + 1, startCopy, substrlength);
753 return start;
755 /* search and replace manipulation */
756 } else {
757 WCHAR *equalspos = strstrW(colonpos, equalsW);
758 WCHAR *replacewith = equalspos+1;
759 WCHAR *found = NULL;
760 WCHAR *searchIn;
761 WCHAR *searchFor;
763 if (equalspos == NULL) return start+1;
764 s = WCMD_strdupW(endOfVar + 1);
766 /* Null terminate both strings */
767 thisVar[strlenW(thisVar)-1] = 0x00;
768 *equalspos = 0x00;
770 /* Since we need to be case insensitive, copy the 2 buffers */
771 searchIn = WCMD_strdupW(thisVarContents);
772 CharUpperBuffW(searchIn, strlenW(thisVarContents));
773 searchFor = WCMD_strdupW(colonpos+1);
774 CharUpperBuffW(searchFor, strlenW(colonpos+1));
776 /* Handle wildcard case */
777 if (*(colonpos+1) == '*') {
778 /* Search for string to replace */
779 found = strstrW(searchIn, searchFor+1);
781 if (found) {
782 /* Do replacement */
783 strcpyW(start, replacewith);
784 strcatW(start, thisVarContents + (found-searchIn) + strlenW(searchFor+1));
785 strcatW(start, s);
786 } else {
787 /* Copy as is */
788 strcpyW(start, thisVarContents);
789 strcatW(start, s);
792 } else {
793 /* Loop replacing all instances */
794 WCHAR *lastFound = searchIn;
795 WCHAR *outputposn = start;
797 *start = 0x00;
798 while ((found = strstrW(lastFound, searchFor))) {
799 lstrcpynW(outputposn,
800 thisVarContents + (lastFound-searchIn),
801 (found - lastFound)+1);
802 outputposn = outputposn + (found - lastFound);
803 strcatW(outputposn, replacewith);
804 outputposn = outputposn + strlenW(replacewith);
805 lastFound = found + strlenW(searchFor);
807 strcatW(outputposn,
808 thisVarContents + (lastFound-searchIn));
809 strcatW(outputposn, s);
811 HeapFree(GetProcessHeap(), 0, s);
812 HeapFree(GetProcessHeap(), 0, searchIn);
813 HeapFree(GetProcessHeap(), 0, searchFor);
814 return start;
816 return start+1;
819 /*****************************************************************************
820 * Expand the command. Native expands lines from batch programs as they are
821 * read in and not again, except for 'for' variable substitution.
822 * eg. As evidence, "echo %1 && shift && echo %1" or "echo %%path%%"
824 static void handleExpansion(WCHAR *cmd, BOOL justFors,
825 const WCHAR *forVariable, const WCHAR *forValue) {
827 /* For commands in a context (batch program): */
828 /* Expand environment variables in a batch file %{0-9} first */
829 /* including support for any ~ modifiers */
830 /* Additionally: */
831 /* Expand the DATE, TIME, CD, RANDOM and ERRORLEVEL special */
832 /* names allowing environment variable overrides */
833 /* NOTE: To support the %PATH:xxx% syntax, also perform */
834 /* manual expansion of environment variables here */
836 WCHAR *p = cmd;
837 WCHAR *t;
838 int i;
840 while ((p = strchrW(p, '%'))) {
842 WINE_TRACE("Translate command:%s %d (at: %s)\n",
843 wine_dbgstr_w(cmd), justFors, wine_dbgstr_w(p));
844 i = *(p+1) - '0';
846 /* Don't touch %% unless its in Batch */
847 if (!justFors && *(p+1) == '%') {
848 if (context) {
849 WCMD_strsubstW(p, p+1, NULL, 0);
851 p+=1;
853 /* Replace %~ modifications if in batch program */
854 } else if (*(p+1) == '~') {
855 WCMD_HandleTildaModifiers(&p, forVariable, forValue, justFors);
856 p++;
858 /* Replace use of %0...%9 if in batch program*/
859 } else if (!justFors && context && (i >= 0) && (i <= 9)) {
860 t = WCMD_parameter(context -> command, i + context -> shift_count[i], NULL, NULL);
861 WCMD_strsubstW(p, p+2, t, -1);
863 /* Replace use of %* if in batch program*/
864 } else if (!justFors && context && *(p+1)=='*') {
865 WCHAR *startOfParms = NULL;
866 t = WCMD_parameter(context -> command, 1, &startOfParms, NULL);
867 if (startOfParms != NULL)
868 WCMD_strsubstW(p, p+2, startOfParms, -1);
869 else
870 WCMD_strsubstW(p, p+2, NULL, 0);
872 } else if (forVariable &&
873 (CompareStringW(LOCALE_USER_DEFAULT,
874 SORT_STRINGSORT,
876 strlenW(forVariable),
877 forVariable, -1) == CSTR_EQUAL)) {
878 WCMD_strsubstW(p, p + strlenW(forVariable), forValue, -1);
880 } else if (!justFors) {
881 p = WCMD_expand_envvar(p, forVariable, forValue);
883 /* In a FOR loop, see if this is the variable to replace */
884 } else { /* Ignore %'s on second pass of batch program */
885 p++;
889 return;
893 /*******************************************************************
894 * WCMD_parse - parse a command into parameters and qualifiers.
896 * On exit, all qualifiers are concatenated into q, the first string
897 * not beginning with "/" is in p1 and the
898 * second in p2. Any subsequent non-qualifier strings are lost.
899 * Parameters in quotes are handled.
901 static void WCMD_parse (const WCHAR *s, WCHAR *q, WCHAR *p1, WCHAR *p2)
903 int p = 0;
905 *q = *p1 = *p2 = '\0';
906 while (TRUE) {
907 switch (*s) {
908 case '/':
909 *q++ = *s++;
910 while ((*s != '\0') && (*s != ' ') && *s != '/') {
911 *q++ = toupperW (*s++);
913 *q = '\0';
914 break;
915 case ' ':
916 case '\t':
917 s++;
918 break;
919 case '"':
920 s++;
921 while ((*s != '\0') && (*s != '"')) {
922 if (p == 0) *p1++ = *s++;
923 else if (p == 1) *p2++ = *s++;
924 else s++;
926 if (p == 0) *p1 = '\0';
927 if (p == 1) *p2 = '\0';
928 p++;
929 if (*s == '"') s++;
930 break;
931 case '\0':
932 return;
933 default:
934 while ((*s != '\0') && (*s != ' ') && (*s != '\t')
935 && (*s != '=') && (*s != ',') ) {
936 if (p == 0) *p1++ = *s++;
937 else if (p == 1) *p2++ = *s++;
938 else s++;
940 /* Skip concurrent parms */
941 while ((*s == ' ') || (*s == '\t') || (*s == '=') || (*s == ',') ) s++;
943 if (p == 0) *p1 = '\0';
944 if (p == 1) *p2 = '\0';
945 p++;
950 static void init_msvcrt_io_block(STARTUPINFOW* st)
952 STARTUPINFOW st_p;
953 /* fetch the parent MSVCRT info block if any, so that the child can use the
954 * same handles as its grand-father
956 st_p.cb = sizeof(STARTUPINFOW);
957 GetStartupInfoW(&st_p);
958 st->cbReserved2 = st_p.cbReserved2;
959 st->lpReserved2 = st_p.lpReserved2;
960 if (st_p.cbReserved2 && st_p.lpReserved2)
962 /* Override the entries for fd 0,1,2 if we happened
963 * to change those std handles (this depends on the way cmd sets
964 * its new input & output handles)
966 size_t sz = max(sizeof(unsigned) + (sizeof(char) + sizeof(HANDLE)) * 3, st_p.cbReserved2);
967 BYTE* ptr = HeapAlloc(GetProcessHeap(), 0, sz);
968 if (ptr)
970 unsigned num = *(unsigned*)st_p.lpReserved2;
971 char* flags = (char*)(ptr + sizeof(unsigned));
972 HANDLE* handles = (HANDLE*)(flags + num * sizeof(char));
974 memcpy(ptr, st_p.lpReserved2, st_p.cbReserved2);
975 st->cbReserved2 = sz;
976 st->lpReserved2 = ptr;
978 #define WX_OPEN 0x01 /* see dlls/msvcrt/file.c */
979 if (num <= 0 || (flags[0] & WX_OPEN))
981 handles[0] = GetStdHandle(STD_INPUT_HANDLE);
982 flags[0] |= WX_OPEN;
984 if (num <= 1 || (flags[1] & WX_OPEN))
986 handles[1] = GetStdHandle(STD_OUTPUT_HANDLE);
987 flags[1] |= WX_OPEN;
989 if (num <= 2 || (flags[2] & WX_OPEN))
991 handles[2] = GetStdHandle(STD_ERROR_HANDLE);
992 flags[2] |= WX_OPEN;
994 #undef WX_OPEN
999 /******************************************************************************
1000 * WCMD_run_program
1002 * Execute a command line as an external program. Must allow recursion.
1004 * Precedence:
1005 * Manual testing under windows shows PATHEXT plays a key part in this,
1006 * and the search algorithm and precedence appears to be as follows.
1008 * Search locations:
1009 * If directory supplied on command, just use that directory
1010 * If extension supplied on command, look for that explicit name first
1011 * Otherwise, search in each directory on the path
1012 * Precedence:
1013 * If extension supplied on command, look for that explicit name first
1014 * Then look for supplied name .* (even if extension supplied, so
1015 * 'garbage.exe' will match 'garbage.exe.cmd')
1016 * If any found, cycle through PATHEXT looking for name.exe one by one
1017 * Launching
1018 * Once a match has been found, it is launched - Code currently uses
1019 * findexecutable to achieve this which is left untouched.
1022 void WCMD_run_program (WCHAR *command, int called) {
1024 WCHAR temp[MAX_PATH];
1025 WCHAR pathtosearch[MAXSTRING];
1026 WCHAR *pathposn;
1027 WCHAR stemofsearch[MAX_PATH]; /* maximum allowed executable name is
1028 MAX_PATH, including null character */
1029 WCHAR *lastSlash;
1030 WCHAR pathext[MAXSTRING];
1031 BOOL extensionsupplied = FALSE;
1032 BOOL launched = FALSE;
1033 BOOL status;
1034 BOOL assumeInternal = FALSE;
1035 DWORD len;
1036 static const WCHAR envPath[] = {'P','A','T','H','\0'};
1037 static const WCHAR envPathExt[] = {'P','A','T','H','E','X','T','\0'};
1038 static const WCHAR delims[] = {'/','\\',':','\0'};
1040 WCMD_parse (command, quals, param1, param2); /* Quick way to get the filename */
1041 if (!(*param1) && !(*param2))
1042 return;
1044 /* Calculate the search path and stem to search for */
1045 if (strpbrkW (param1, delims) == NULL) { /* No explicit path given, search path */
1046 static const WCHAR curDir[] = {'.',';','\0'};
1047 strcpyW(pathtosearch, curDir);
1048 len = GetEnvironmentVariableW(envPath, &pathtosearch[2], (sizeof(pathtosearch)/sizeof(WCHAR))-2);
1049 if ((len == 0) || (len >= (sizeof(pathtosearch)/sizeof(WCHAR)) - 2)) {
1050 static const WCHAR curDir[] = {'.','\0'};
1051 strcpyW (pathtosearch, curDir);
1053 if (strchrW(param1, '.') != NULL) extensionsupplied = TRUE;
1054 if (strlenW(param1) >= MAX_PATH)
1056 WCMD_output_asis_stderr(WCMD_LoadMessage(WCMD_LINETOOLONG));
1057 return;
1060 strcpyW(stemofsearch, param1);
1062 } else {
1064 /* Convert eg. ..\fred to include a directory by removing file part */
1065 GetFullPathNameW(param1, sizeof(pathtosearch)/sizeof(WCHAR), pathtosearch, NULL);
1066 lastSlash = strrchrW(pathtosearch, '\\');
1067 if (lastSlash && strchrW(lastSlash, '.') != NULL) extensionsupplied = TRUE;
1068 strcpyW(stemofsearch, lastSlash+1);
1070 /* Reduce pathtosearch to a path with trailing '\' to support c:\a.bat and
1071 c:\windows\a.bat syntax */
1072 if (lastSlash) *(lastSlash + 1) = 0x00;
1075 /* Now extract PATHEXT */
1076 len = GetEnvironmentVariableW(envPathExt, pathext, sizeof(pathext)/sizeof(WCHAR));
1077 if ((len == 0) || (len >= (sizeof(pathext)/sizeof(WCHAR)))) {
1078 static const WCHAR dfltPathExt[] = {'.','b','a','t',';',
1079 '.','c','o','m',';',
1080 '.','c','m','d',';',
1081 '.','e','x','e','\0'};
1082 strcpyW (pathext, dfltPathExt);
1085 /* Loop through the search path, dir by dir */
1086 pathposn = pathtosearch;
1087 WINE_TRACE("Searching in '%s' for '%s'\n", wine_dbgstr_w(pathtosearch),
1088 wine_dbgstr_w(stemofsearch));
1089 while (!launched && pathposn) {
1091 WCHAR thisDir[MAX_PATH] = {'\0'};
1092 WCHAR *pos = NULL;
1093 BOOL found = FALSE;
1094 static const WCHAR slashW[] = {'\\','\0'};
1096 /* Work on the first directory on the search path */
1097 pos = strchrW(pathposn, ';');
1098 if (pos) {
1099 memcpy(thisDir, pathposn, (pos-pathposn) * sizeof(WCHAR));
1100 thisDir[(pos-pathposn)] = 0x00;
1101 pathposn = pos+1;
1103 } else {
1104 strcpyW(thisDir, pathposn);
1105 pathposn = NULL;
1108 /* Since you can have eg. ..\.. on the path, need to expand
1109 to full information */
1110 strcpyW(temp, thisDir);
1111 GetFullPathNameW(temp, MAX_PATH, thisDir, NULL);
1113 /* 1. If extension supplied, see if that file exists */
1114 strcatW(thisDir, slashW);
1115 strcatW(thisDir, stemofsearch);
1116 pos = &thisDir[strlenW(thisDir)]; /* Pos = end of name */
1118 /* 1. If extension supplied, see if that file exists */
1119 if (extensionsupplied) {
1120 if (GetFileAttributesW(thisDir) != INVALID_FILE_ATTRIBUTES) {
1121 found = TRUE;
1125 /* 2. Any .* matches? */
1126 if (!found) {
1127 HANDLE h;
1128 WIN32_FIND_DATAW finddata;
1129 static const WCHAR allFiles[] = {'.','*','\0'};
1131 strcatW(thisDir,allFiles);
1132 h = FindFirstFileW(thisDir, &finddata);
1133 FindClose(h);
1134 if (h != INVALID_HANDLE_VALUE) {
1136 WCHAR *thisExt = pathext;
1138 /* 3. Yes - Try each path ext */
1139 while (thisExt) {
1140 WCHAR *nextExt = strchrW(thisExt, ';');
1142 if (nextExt) {
1143 memcpy(pos, thisExt, (nextExt-thisExt) * sizeof(WCHAR));
1144 pos[(nextExt-thisExt)] = 0x00;
1145 thisExt = nextExt+1;
1146 } else {
1147 strcpyW(pos, thisExt);
1148 thisExt = NULL;
1151 if (GetFileAttributesW(thisDir) != INVALID_FILE_ATTRIBUTES) {
1152 found = TRUE;
1153 thisExt = NULL;
1159 /* Internal programs won't be picked up by this search, so even
1160 though not found, try one last createprocess and wait for it
1161 to complete.
1162 Note: Ideally we could tell between a console app (wait) and a
1163 windows app, but the API's for it fail in this case */
1164 if (!found && pathposn == NULL) {
1165 WINE_TRACE("ASSUMING INTERNAL\n");
1166 assumeInternal = TRUE;
1167 } else {
1168 WINE_TRACE("Found as %s\n", wine_dbgstr_w(thisDir));
1171 /* Once found, launch it */
1172 if (found || assumeInternal) {
1173 STARTUPINFOW st;
1174 PROCESS_INFORMATION pe;
1175 SHFILEINFOW psfi;
1176 DWORD console;
1177 HINSTANCE hinst;
1178 WCHAR *ext = strrchrW( thisDir, '.' );
1179 static const WCHAR batExt[] = {'.','b','a','t','\0'};
1180 static const WCHAR cmdExt[] = {'.','c','m','d','\0'};
1182 launched = TRUE;
1184 /* Special case BAT and CMD */
1185 if (ext && !strcmpiW(ext, batExt)) {
1186 WCMD_batch (thisDir, command, called, NULL, INVALID_HANDLE_VALUE);
1187 return;
1188 } else if (ext && !strcmpiW(ext, cmdExt)) {
1189 WCMD_batch (thisDir, command, called, NULL, INVALID_HANDLE_VALUE);
1190 return;
1191 } else {
1193 /* thisDir contains the file to be launched, but with what?
1194 eg. a.exe will require a.exe to be launched, a.html may be iexplore */
1195 hinst = FindExecutableW (thisDir, NULL, temp);
1196 if ((INT_PTR)hinst < 32)
1197 console = 0;
1198 else
1199 console = SHGetFileInfoW(temp, 0, &psfi, sizeof(psfi), SHGFI_EXETYPE);
1201 ZeroMemory (&st, sizeof(STARTUPINFOW));
1202 st.cb = sizeof(STARTUPINFOW);
1203 init_msvcrt_io_block(&st);
1205 /* Launch the process and if a CUI wait on it to complete
1206 Note: Launching internal wine processes cannot specify a full path to exe */
1207 status = CreateProcessW(assumeInternal?NULL : thisDir,
1208 command, NULL, NULL, TRUE, 0, NULL, NULL, &st, &pe);
1209 if ((opt_c || opt_k) && !opt_s && !status
1210 && GetLastError()==ERROR_FILE_NOT_FOUND && command[0]=='\"') {
1211 /* strip first and last quote WCHARacters and try again */
1212 WCMD_opt_s_strip_quotes(command);
1213 opt_s=1;
1214 WCMD_run_program(command, called);
1215 return;
1218 if (!status)
1219 break;
1221 if (!assumeInternal && !console) errorlevel = 0;
1222 else
1224 /* Always wait when called in a batch program context */
1225 if (assumeInternal || context || !HIWORD(console)) WaitForSingleObject (pe.hProcess, INFINITE);
1226 GetExitCodeProcess (pe.hProcess, &errorlevel);
1227 if (errorlevel == STILL_ACTIVE) errorlevel = 0;
1229 CloseHandle(pe.hProcess);
1230 CloseHandle(pe.hThread);
1231 return;
1236 /* Not found anywhere - give up */
1237 SetLastError(ERROR_FILE_NOT_FOUND);
1238 WCMD_print_error ();
1240 /* If a command fails to launch, it sets errorlevel 9009 - which
1241 does not seem to have any associated constant definition */
1242 errorlevel = 9009;
1243 return;
1247 /*****************************************************************************
1248 * Process one command. If the command is EXIT this routine does not return.
1249 * We will recurse through here executing batch files.
1251 void WCMD_execute (const WCHAR *command, const WCHAR *redirects,
1252 const WCHAR *forVariable, const WCHAR *forValue,
1253 CMD_LIST **cmdList)
1255 WCHAR *cmd, *p, *redir;
1256 int status, i;
1257 DWORD count, creationDisposition;
1258 HANDLE h;
1259 WCHAR *whichcmd;
1260 SECURITY_ATTRIBUTES sa;
1261 WCHAR *new_cmd = NULL;
1262 WCHAR *new_redir = NULL;
1263 HANDLE old_stdhandles[3] = {GetStdHandle (STD_INPUT_HANDLE),
1264 GetStdHandle (STD_OUTPUT_HANDLE),
1265 GetStdHandle (STD_ERROR_HANDLE)};
1266 DWORD idx_stdhandles[3] = {STD_INPUT_HANDLE,
1267 STD_OUTPUT_HANDLE,
1268 STD_ERROR_HANDLE};
1269 BOOL prev_echo_mode, piped = FALSE;
1271 WINE_TRACE("command on entry:%s (%p), with forVariable '%s'='%s'\n",
1272 wine_dbgstr_w(command), cmdList,
1273 wine_dbgstr_w(forVariable), wine_dbgstr_w(forValue));
1275 /* If the next command is a pipe then we implement pipes by redirecting
1276 the output from this command to a temp file and input into the
1277 next command from that temp file.
1278 FIXME: Use of named pipes would make more sense here as currently this
1279 process has to finish before the next one can start but this requires
1280 a change to not wait for the first app to finish but rather the pipe */
1281 if (cmdList && (*cmdList)->nextcommand &&
1282 (*cmdList)->nextcommand->prevDelim == CMD_PIPE) {
1284 WCHAR temp_path[MAX_PATH];
1285 static const WCHAR cmdW[] = {'C','M','D','\0'};
1287 /* Remember piping is in action */
1288 WINE_TRACE("Output needs to be piped\n");
1289 piped = TRUE;
1291 /* Generate a unique temporary filename */
1292 GetTempPathW(sizeof(temp_path)/sizeof(WCHAR), temp_path);
1293 GetTempFileNameW(temp_path, cmdW, 0, (*cmdList)->nextcommand->pipeFile);
1294 WINE_TRACE("Using temporary file of %s\n",
1295 wine_dbgstr_w((*cmdList)->nextcommand->pipeFile));
1298 /* Move copy of the command onto the heap so it can be expanded */
1299 new_cmd = HeapAlloc( GetProcessHeap(), 0, MAXSTRING * sizeof(WCHAR));
1300 if (!new_cmd)
1302 WINE_ERR("Could not allocate memory for new_cmd\n");
1303 return;
1305 strcpyW(new_cmd, command);
1307 /* Move copy of the redirects onto the heap so it can be expanded */
1308 new_redir = HeapAlloc( GetProcessHeap(), 0, MAXSTRING * sizeof(WCHAR));
1309 if (!new_redir)
1311 WINE_ERR("Could not allocate memory for new_redir\n");
1312 HeapFree( GetProcessHeap(), 0, new_cmd );
1313 return;
1316 /* If piped output, send stdout to the pipe by appending >filename to redirects */
1317 if (piped) {
1318 static const WCHAR redirOut[] = {'%','s',' ','>',' ','%','s','\0'};
1319 wsprintfW (new_redir, redirOut, redirects, (*cmdList)->nextcommand->pipeFile);
1320 WINE_TRACE("Redirects now %s\n", wine_dbgstr_w(new_redir));
1321 } else {
1322 strcpyW(new_redir, redirects);
1325 /* Expand variables in command line mode only (batch mode will
1326 be expanded as the line is read in, except for 'for' loops) */
1327 handleExpansion(new_cmd, (context != NULL), forVariable, forValue);
1328 handleExpansion(new_redir, (context != NULL), forVariable, forValue);
1329 cmd = new_cmd;
1332 * Changing default drive has to be handled as a special case.
1335 if ((cmd[1] == ':') && IsCharAlphaW(cmd[0]) && (strlenW(cmd) == 2)) {
1336 WCHAR envvar[5];
1337 WCHAR dir[MAX_PATH];
1339 /* According to MSDN CreateProcess docs, special env vars record
1340 the current directory on each drive, in the form =C:
1341 so see if one specified, and if so go back to it */
1342 strcpyW(envvar, equalsW);
1343 strcatW(envvar, cmd);
1344 if (GetEnvironmentVariableW(envvar, dir, MAX_PATH) == 0) {
1345 static const WCHAR fmt[] = {'%','s','\\','\0'};
1346 wsprintfW(cmd, fmt, cmd);
1347 WINE_TRACE("No special directory settings, using dir of %s\n", wine_dbgstr_w(cmd));
1349 WINE_TRACE("Got directory %s as %s\n", wine_dbgstr_w(envvar), wine_dbgstr_w(cmd));
1350 status = SetCurrentDirectoryW(cmd);
1351 if (!status) WCMD_print_error ();
1352 HeapFree( GetProcessHeap(), 0, cmd );
1353 HeapFree( GetProcessHeap(), 0, new_redir );
1354 return;
1357 sa.nLength = sizeof(sa);
1358 sa.lpSecurityDescriptor = NULL;
1359 sa.bInheritHandle = TRUE;
1362 * Redirect stdin, stdout and/or stderr if required.
1365 /* STDIN could come from a preceding pipe, so delete on close if it does */
1366 if (cmdList && (*cmdList)->pipeFile[0] != 0x00) {
1367 WINE_TRACE("Input coming from %s\n", wine_dbgstr_w((*cmdList)->pipeFile));
1368 h = CreateFileW((*cmdList)->pipeFile, GENERIC_READ,
1369 FILE_SHARE_READ, &sa, OPEN_EXISTING,
1370 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE, NULL);
1371 if (h == INVALID_HANDLE_VALUE) {
1372 WCMD_print_error ();
1373 HeapFree( GetProcessHeap(), 0, cmd );
1374 HeapFree( GetProcessHeap(), 0, new_redir );
1375 return;
1377 SetStdHandle (STD_INPUT_HANDLE, h);
1379 /* No need to remember the temporary name any longer once opened */
1380 (*cmdList)->pipeFile[0] = 0x00;
1382 /* Otherwise STDIN could come from a '<' redirect */
1383 } else if ((p = strchrW(new_redir,'<')) != NULL) {
1384 h = CreateFileW(WCMD_parameter(++p, 0, NULL, NULL), GENERIC_READ, FILE_SHARE_READ,
1385 &sa, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
1386 if (h == INVALID_HANDLE_VALUE) {
1387 WCMD_print_error ();
1388 HeapFree( GetProcessHeap(), 0, cmd );
1389 HeapFree( GetProcessHeap(), 0, new_redir );
1390 return;
1392 SetStdHandle (STD_INPUT_HANDLE, h);
1395 /* Scan the whole command looking for > and 2> */
1396 redir = new_redir;
1397 while (redir != NULL && ((p = strchrW(redir,'>')) != NULL)) {
1398 int handle = 0;
1400 if (p > redir && (*(p-1)=='2'))
1401 handle = 2;
1402 else
1403 handle = 1;
1405 p++;
1406 if ('>' == *p) {
1407 creationDisposition = OPEN_ALWAYS;
1408 p++;
1410 else {
1411 creationDisposition = CREATE_ALWAYS;
1414 /* Add support for 2>&1 */
1415 redir = p;
1416 if (*p == '&') {
1417 int idx = *(p+1) - '0';
1419 if (DuplicateHandle(GetCurrentProcess(),
1420 GetStdHandle(idx_stdhandles[idx]),
1421 GetCurrentProcess(),
1423 0, TRUE, DUPLICATE_SAME_ACCESS) == 0) {
1424 WINE_FIXME("Duplicating handle failed with gle %d\n", GetLastError());
1426 WINE_TRACE("Redirect %d (%p) to %d (%p)\n", handle, GetStdHandle(idx_stdhandles[idx]), idx, h);
1428 } else {
1429 WCHAR *param = WCMD_parameter(p, 0, NULL, NULL);
1430 h = CreateFileW(param, GENERIC_WRITE, 0, &sa, creationDisposition,
1431 FILE_ATTRIBUTE_NORMAL, NULL);
1432 if (h == INVALID_HANDLE_VALUE) {
1433 WCMD_print_error ();
1434 HeapFree( GetProcessHeap(), 0, cmd );
1435 HeapFree( GetProcessHeap(), 0, new_redir );
1436 return;
1438 if (SetFilePointer (h, 0, NULL, FILE_END) ==
1439 INVALID_SET_FILE_POINTER) {
1440 WCMD_print_error ();
1442 WINE_TRACE("Redirect %d to '%s' (%p)\n", handle, wine_dbgstr_w(param), h);
1445 SetStdHandle (idx_stdhandles[handle], h);
1449 * Strip leading whitespaces, and a '@' if supplied
1451 whichcmd = WCMD_skip_leading_spaces(cmd);
1452 WINE_TRACE("Command: '%s'\n", wine_dbgstr_w(cmd));
1453 if (whichcmd[0] == '@') whichcmd++;
1456 * Check if the command entered is internal. If it is, pass the rest of the
1457 * line down to the command. If not try to run a program.
1460 count = 0;
1461 while (IsCharAlphaNumericW(whichcmd[count])) {
1462 count++;
1464 for (i=0; i<=WCMD_EXIT; i++) {
1465 if (CompareStringW(LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
1466 whichcmd, count, inbuilt[i], -1) == CSTR_EQUAL) break;
1468 p = WCMD_skip_leading_spaces (&whichcmd[count]);
1469 WCMD_parse (p, quals, param1, param2);
1470 WINE_TRACE("param1: %s, param2: %s\n", wine_dbgstr_w(param1), wine_dbgstr_w(param2));
1472 if (i <= WCMD_EXIT && (p[0] == '/') && (p[1] == '?')) {
1473 /* this is a help request for a builtin program */
1474 i = WCMD_HELP;
1475 memcpy(p, whichcmd, count * sizeof(WCHAR));
1476 p[count] = '\0';
1480 switch (i) {
1482 case WCMD_CALL:
1483 WCMD_call (p);
1484 break;
1485 case WCMD_CD:
1486 case WCMD_CHDIR:
1487 WCMD_setshow_default (p);
1488 break;
1489 case WCMD_CLS:
1490 WCMD_clear_screen ();
1491 break;
1492 case WCMD_COPY:
1493 WCMD_copy ();
1494 break;
1495 case WCMD_CTTY:
1496 WCMD_change_tty ();
1497 break;
1498 case WCMD_DATE:
1499 WCMD_setshow_date ();
1500 break;
1501 case WCMD_DEL:
1502 case WCMD_ERASE:
1503 WCMD_delete (p);
1504 break;
1505 case WCMD_DIR:
1506 WCMD_directory (p);
1507 break;
1508 case WCMD_ECHO:
1509 WCMD_echo(&whichcmd[count]);
1510 break;
1511 case WCMD_FOR:
1512 WCMD_for (p, cmdList);
1513 break;
1514 case WCMD_GOTO:
1515 WCMD_goto (cmdList);
1516 break;
1517 case WCMD_HELP:
1518 WCMD_give_help (p);
1519 break;
1520 case WCMD_IF:
1521 WCMD_if (p, cmdList);
1522 break;
1523 case WCMD_LABEL:
1524 WCMD_volume (TRUE, p);
1525 break;
1526 case WCMD_MD:
1527 case WCMD_MKDIR:
1528 WCMD_create_dir (p);
1529 break;
1530 case WCMD_MOVE:
1531 WCMD_move ();
1532 break;
1533 case WCMD_PATH:
1534 WCMD_setshow_path (p);
1535 break;
1536 case WCMD_PAUSE:
1537 WCMD_pause ();
1538 break;
1539 case WCMD_PROMPT:
1540 WCMD_setshow_prompt ();
1541 break;
1542 case WCMD_REM:
1543 break;
1544 case WCMD_REN:
1545 case WCMD_RENAME:
1546 WCMD_rename ();
1547 break;
1548 case WCMD_RD:
1549 case WCMD_RMDIR:
1550 WCMD_remove_dir (p);
1551 break;
1552 case WCMD_SETLOCAL:
1553 WCMD_setlocal(p);
1554 break;
1555 case WCMD_ENDLOCAL:
1556 WCMD_endlocal();
1557 break;
1558 case WCMD_SET:
1559 WCMD_setshow_env (p);
1560 break;
1561 case WCMD_SHIFT:
1562 WCMD_shift (p);
1563 break;
1564 case WCMD_TIME:
1565 WCMD_setshow_time ();
1566 break;
1567 case WCMD_TITLE:
1568 if (strlenW(&whichcmd[count]) > 0)
1569 WCMD_title(&whichcmd[count+1]);
1570 break;
1571 case WCMD_TYPE:
1572 WCMD_type (p);
1573 break;
1574 case WCMD_VER:
1575 WCMD_output(newline);
1576 WCMD_version ();
1577 break;
1578 case WCMD_VERIFY:
1579 WCMD_verify (p);
1580 break;
1581 case WCMD_VOL:
1582 WCMD_volume (FALSE, p);
1583 break;
1584 case WCMD_PUSHD:
1585 WCMD_pushd(p);
1586 break;
1587 case WCMD_POPD:
1588 WCMD_popd();
1589 break;
1590 case WCMD_ASSOC:
1591 WCMD_assoc(p, TRUE);
1592 break;
1593 case WCMD_COLOR:
1594 WCMD_color();
1595 break;
1596 case WCMD_FTYPE:
1597 WCMD_assoc(p, FALSE);
1598 break;
1599 case WCMD_MORE:
1600 WCMD_more(p);
1601 break;
1602 case WCMD_CHOICE:
1603 WCMD_choice(p);
1604 break;
1605 case WCMD_EXIT:
1606 WCMD_exit (cmdList);
1607 break;
1608 default:
1609 prev_echo_mode = echo_mode;
1610 WCMD_run_program (whichcmd, 0);
1611 echo_mode = prev_echo_mode;
1613 HeapFree( GetProcessHeap(), 0, cmd );
1614 HeapFree( GetProcessHeap(), 0, new_redir );
1616 /* Restore old handles */
1617 for (i=0; i<3; i++) {
1618 if (old_stdhandles[i] != GetStdHandle(idx_stdhandles[i])) {
1619 CloseHandle (GetStdHandle (idx_stdhandles[i]));
1620 SetStdHandle (idx_stdhandles[i], old_stdhandles[i]);
1625 /*************************************************************************
1626 * WCMD_LoadMessage
1627 * Load a string from the resource file, handling any error
1628 * Returns string retrieved from resource file
1630 WCHAR *WCMD_LoadMessage(UINT id) {
1631 static WCHAR msg[2048];
1632 static const WCHAR failedMsg[] = {'F','a','i','l','e','d','!','\0'};
1634 if (!LoadStringW(GetModuleHandleW(NULL), id, msg, sizeof(msg)/sizeof(WCHAR))) {
1635 WINE_FIXME("LoadString failed with %d\n", GetLastError());
1636 strcpyW(msg, failedMsg);
1638 return msg;
1641 /***************************************************************************
1642 * WCMD_DumpCommands
1644 * Dumps out the parsed command line to ensure syntax is correct
1646 static void WCMD_DumpCommands(CMD_LIST *commands) {
1647 CMD_LIST *thisCmd = commands;
1649 WINE_TRACE("Parsed line:\n");
1650 while (thisCmd != NULL) {
1651 WINE_TRACE("%p %d %2.2d %p %s Redir:%s\n",
1652 thisCmd,
1653 thisCmd->prevDelim,
1654 thisCmd->bracketDepth,
1655 thisCmd->nextcommand,
1656 wine_dbgstr_w(thisCmd->command),
1657 wine_dbgstr_w(thisCmd->redirects));
1658 thisCmd = thisCmd->nextcommand;
1662 /***************************************************************************
1663 * WCMD_addCommand
1665 * Adds a command to the current command list
1667 static void WCMD_addCommand(WCHAR *command, int *commandLen,
1668 WCHAR *redirs, int *redirLen,
1669 WCHAR **copyTo, int **copyToLen,
1670 CMD_DELIMITERS prevDelim, int curDepth,
1671 CMD_LIST **lastEntry, CMD_LIST **output) {
1673 CMD_LIST *thisEntry = NULL;
1675 /* Allocate storage for command */
1676 thisEntry = HeapAlloc(GetProcessHeap(), 0, sizeof(CMD_LIST));
1678 /* Copy in the command */
1679 if (command) {
1680 thisEntry->command = HeapAlloc(GetProcessHeap(), 0,
1681 (*commandLen+1) * sizeof(WCHAR));
1682 memcpy(thisEntry->command, command, *commandLen * sizeof(WCHAR));
1683 thisEntry->command[*commandLen] = 0x00;
1685 /* Copy in the redirects */
1686 thisEntry->redirects = HeapAlloc(GetProcessHeap(), 0,
1687 (*redirLen+1) * sizeof(WCHAR));
1688 memcpy(thisEntry->redirects, redirs, *redirLen * sizeof(WCHAR));
1689 thisEntry->redirects[*redirLen] = 0x00;
1690 thisEntry->pipeFile[0] = 0x00;
1692 /* Reset the lengths */
1693 *commandLen = 0;
1694 *redirLen = 0;
1695 *copyToLen = commandLen;
1696 *copyTo = command;
1698 } else {
1699 thisEntry->command = NULL;
1700 thisEntry->redirects = NULL;
1701 thisEntry->pipeFile[0] = 0x00;
1704 /* Fill in other fields */
1705 thisEntry->nextcommand = NULL;
1706 thisEntry->prevDelim = prevDelim;
1707 thisEntry->bracketDepth = curDepth;
1708 if (*lastEntry) {
1709 (*lastEntry)->nextcommand = thisEntry;
1710 } else {
1711 *output = thisEntry;
1713 *lastEntry = thisEntry;
1717 /***************************************************************************
1718 * WCMD_IsEndQuote
1720 * Checks if the quote pointed to is the end-quote.
1722 * Quotes end if:
1724 * 1) The current parameter ends at EOL or at the beginning
1725 * of a redirection or pipe and not in a quote section.
1727 * 2) If the next character is a space and not in a quote section.
1729 * Returns TRUE if this is an end quote, and FALSE if it is not.
1732 static BOOL WCMD_IsEndQuote(const WCHAR *quote, int quoteIndex)
1734 int quoteCount = quoteIndex;
1735 int i;
1737 /* If we are not in a quoted section, then we are not an end-quote */
1738 if(quoteIndex == 0)
1740 return FALSE;
1743 /* Check how many quotes are left for this parameter */
1744 for(i=0;quote[i];i++)
1746 if(quote[i] == '"')
1748 quoteCount++;
1751 /* Quote counting ends at EOL, redirection, space or pipe if current quote is complete */
1752 else if(((quoteCount % 2) == 0)
1753 && ((quote[i] == '<') || (quote[i] == '>') || (quote[i] == '|') || (quote[i] == ' ')))
1755 break;
1759 /* If the quote is part of the last part of a series of quotes-on-quotes, then it must
1760 be an end-quote */
1761 if(quoteIndex >= (quoteCount / 2))
1763 return TRUE;
1766 /* No cigar */
1767 return FALSE;
1770 /***************************************************************************
1771 * WCMD_ReadAndParseLine
1773 * Either uses supplied input or
1774 * Reads a file from the handle, and then...
1775 * Parse the text buffer, splitting into separate commands
1776 * - unquoted && strings split 2 commands but the 2nd is flagged as
1777 * following an &&
1778 * - ( as the first character just ups the bracket depth
1779 * - unquoted ) when bracket depth > 0 terminates a bracket and
1780 * adds a CMD_LIST structure with null command
1781 * - Anything else gets put into the command string (including
1782 * redirects)
1784 WCHAR *WCMD_ReadAndParseLine(const WCHAR *optionalcmd, CMD_LIST **output,
1785 HANDLE readFrom, const BOOL is_console_handle)
1787 WCHAR *curPos;
1788 int inQuotes = 0;
1789 WCHAR curString[MAXSTRING];
1790 int curStringLen = 0;
1791 WCHAR curRedirs[MAXSTRING];
1792 int curRedirsLen = 0;
1793 WCHAR *curCopyTo;
1794 int *curLen;
1795 int curDepth = 0;
1796 CMD_LIST *lastEntry = NULL;
1797 CMD_DELIMITERS prevDelim = CMD_NONE;
1798 static WCHAR *extraSpace = NULL; /* Deliberately never freed */
1799 static const WCHAR remCmd[] = {'r','e','m'};
1800 static const WCHAR forCmd[] = {'f','o','r'};
1801 static const WCHAR ifCmd[] = {'i','f'};
1802 static const WCHAR ifElse[] = {'e','l','s','e'};
1803 BOOL inRem = FALSE;
1804 BOOL inFor = FALSE;
1805 BOOL inIn = FALSE;
1806 BOOL inIf = FALSE;
1807 BOOL inElse= FALSE;
1808 BOOL onlyWhiteSpace = FALSE;
1809 BOOL lastWasWhiteSpace = FALSE;
1810 BOOL lastWasDo = FALSE;
1811 BOOL lastWasIn = FALSE;
1812 BOOL lastWasElse = FALSE;
1813 BOOL lastWasRedirect = TRUE;
1815 /* Allocate working space for a command read from keyboard, file etc */
1816 if (!extraSpace)
1817 extraSpace = HeapAlloc(GetProcessHeap(), 0, (MAXSTRING+1) * sizeof(WCHAR));
1818 if (!extraSpace)
1820 WINE_ERR("Could not allocate memory for extraSpace\n");
1821 return NULL;
1824 /* If initial command read in, use that, otherwise get input from handle */
1825 if (optionalcmd != NULL) {
1826 strcpyW(extraSpace, optionalcmd);
1827 } else if (readFrom == INVALID_HANDLE_VALUE) {
1828 WINE_FIXME("No command nor handle supplied\n");
1829 } else {
1830 if (!WCMD_fgets(extraSpace, MAXSTRING, readFrom, is_console_handle))
1831 return NULL;
1833 curPos = extraSpace;
1835 /* Handle truncated input - issue warning */
1836 if (strlenW(extraSpace) == MAXSTRING -1) {
1837 WCMD_output_asis_stderr(WCMD_LoadMessage(WCMD_TRUNCATEDLINE));
1838 WCMD_output_asis_stderr(extraSpace);
1839 WCMD_output_asis_stderr(newline);
1842 /* Replace env vars if in a batch context */
1843 if (context) handleExpansion(extraSpace, FALSE, NULL, NULL);
1844 /* Show prompt before batch line IF echo is on and in batch program */
1845 if (context && echo_mode && extraSpace[0] && (extraSpace[0] != '@')) {
1846 static const WCHAR spc[]={' ','\0'};
1847 static const WCHAR echoDot[] = {'e','c','h','o','.'};
1848 static const WCHAR echoCol[] = {'e','c','h','o',':'};
1849 const DWORD len = sizeof(echoDot)/sizeof(echoDot[0]);
1850 DWORD curr_size = strlenW(extraSpace);
1851 DWORD min_len = (curr_size < len ? curr_size : len);
1852 WCMD_show_prompt();
1853 WCMD_output_asis(extraSpace);
1854 /* I don't know why Windows puts a space here but it does */
1855 /* Except for lines starting with 'echo.' or 'echo:'. Ask MS why */
1856 if (CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
1857 extraSpace, min_len, echoDot, len) != CSTR_EQUAL
1858 && CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
1859 extraSpace, min_len, echoCol, len) != CSTR_EQUAL)
1861 WCMD_output_asis(spc);
1863 WCMD_output_asis(newline);
1866 /* Start with an empty string, copying to the command string */
1867 curStringLen = 0;
1868 curRedirsLen = 0;
1869 curCopyTo = curString;
1870 curLen = &curStringLen;
1871 lastWasRedirect = FALSE; /* Required for eg spaces between > and filename */
1873 /* Parse every character on the line being processed */
1874 while (*curPos != 0x00) {
1876 WCHAR thisChar;
1878 /* Debugging AID:
1879 WINE_TRACE("Looking at '%c' (len:%d, lws:%d, ows:%d)\n", *curPos, *curLen,
1880 lastWasWhiteSpace, onlyWhiteSpace);
1883 /* Certain commands need special handling */
1884 if (curStringLen == 0 && curCopyTo == curString) {
1885 static const WCHAR forDO[] = {'d','o'};
1887 /* If command starts with 'rem ', ignore any &&, ( etc. */
1888 if (WCMD_keyword_ws_found(remCmd, sizeof(remCmd)/sizeof(remCmd[0]), curPos)) {
1889 inRem = TRUE;
1891 } else if (WCMD_keyword_ws_found(forCmd, sizeof(forCmd)/sizeof(forCmd[0]), curPos)) {
1892 inFor = TRUE;
1894 /* If command starts with 'if ' or 'else ', handle ('s mid line. We should ensure this
1895 is only true in the command portion of the IF statement, but this
1896 should suffice for now
1897 FIXME: Silly syntax like "if 1(==1( (
1898 echo they equal
1899 )" will be parsed wrong */
1900 } else if (WCMD_keyword_ws_found(ifCmd, sizeof(ifCmd)/sizeof(ifCmd[0]), curPos)) {
1901 inIf = TRUE;
1903 } else if (WCMD_keyword_ws_found(ifElse, sizeof(ifElse)/sizeof(ifElse[0]), curPos)) {
1904 const int keyw_len = sizeof(ifElse)/sizeof(ifElse[0]) + 1;
1905 inElse = TRUE;
1906 lastWasElse = TRUE;
1907 onlyWhiteSpace = TRUE;
1908 memcpy(&curCopyTo[*curLen], curPos, keyw_len*sizeof(WCHAR));
1909 (*curLen)+=keyw_len;
1910 curPos+=keyw_len;
1911 continue;
1913 /* In a for loop, the DO command will follow a close bracket followed by
1914 whitespace, followed by DO, ie closeBracket inserts a NULL entry, curLen
1915 is then 0, and all whitespace is skipped */
1916 } else if (inFor &&
1917 WCMD_keyword_ws_found(forDO, sizeof(forDO)/sizeof(forDO[0]), curPos)) {
1918 const int keyw_len = sizeof(forDO)/sizeof(forDO[0]) + 1;
1919 WINE_TRACE("Found 'DO '\n");
1920 lastWasDo = TRUE;
1921 onlyWhiteSpace = TRUE;
1922 memcpy(&curCopyTo[*curLen], curPos, keyw_len*sizeof(WCHAR));
1923 (*curLen)+=keyw_len;
1924 curPos+=keyw_len;
1925 continue;
1927 } else if (curCopyTo == curString) {
1929 /* Special handling for the 'FOR' command */
1930 if (inFor && lastWasWhiteSpace) {
1931 static const WCHAR forIN[] = {'i','n'};
1933 WINE_TRACE("Found 'FOR ', comparing next parm: '%s'\n", wine_dbgstr_w(curPos));
1935 if (WCMD_keyword_ws_found(forIN, sizeof(forIN)/sizeof(forIN[0]), curPos)) {
1936 const int keyw_len = sizeof(forIN)/sizeof(forIN[0]) + 1;
1937 WINE_TRACE("Found 'IN '\n");
1938 lastWasIn = TRUE;
1939 onlyWhiteSpace = TRUE;
1940 memcpy(&curCopyTo[*curLen], curPos, keyw_len*sizeof(WCHAR));
1941 (*curLen)+=keyw_len;
1942 curPos+=keyw_len;
1943 continue;
1948 /* Nothing 'ends' a REM statement and &&, quotes etc are ineffective,
1949 so just use the default processing ie skip character specific
1950 matching below */
1951 if (!inRem) thisChar = *curPos;
1952 else thisChar = 'X'; /* Character with no special processing */
1954 lastWasWhiteSpace = FALSE; /* Will be reset below */
1956 switch (thisChar) {
1958 case '=': /* drop through - ignore token delimiters at the start of a command */
1959 case ',': /* drop through - ignore token delimiters at the start of a command */
1960 case '\t':/* drop through - ignore token delimiters at the start of a command */
1961 case ' ':
1962 /* If a redirect in place, it ends here */
1963 if (!inQuotes && !lastWasRedirect) {
1965 /* If finishing off a redirect, add a whitespace delimiter */
1966 if (curCopyTo == curRedirs) {
1967 curCopyTo[(*curLen)++] = ' ';
1969 curCopyTo = curString;
1970 curLen = &curStringLen;
1972 if (*curLen > 0) {
1973 curCopyTo[(*curLen)++] = *curPos;
1976 /* Remember just processed whitespace */
1977 lastWasWhiteSpace = TRUE;
1979 break;
1981 case '>': /* drop through - handle redirect chars the same */
1982 case '<':
1983 /* Make a redirect start here */
1984 if (!inQuotes) {
1985 curCopyTo = curRedirs;
1986 curLen = &curRedirsLen;
1987 lastWasRedirect = TRUE;
1990 /* See if 1>, 2> etc, in which case we have some patching up
1991 to do (provided there's a preceding whitespace, and enough
1992 chars read so far) */
1993 if (curStringLen > 2
1994 && (*(curPos-1)>='1') && (*(curPos-1)<='9')
1995 && ((*(curPos-2)==' ') || (*(curPos-2)=='\t'))) {
1996 curStringLen--;
1997 curString[curStringLen] = 0x00;
1998 curCopyTo[(*curLen)++] = *(curPos-1);
2001 curCopyTo[(*curLen)++] = *curPos;
2003 /* If a redirect is immediately followed by '&' (ie. 2>&1) then
2004 do not process that ampersand as an AND operator */
2005 if (thisChar == '>' && *(curPos+1) == '&') {
2006 curCopyTo[(*curLen)++] = *(curPos+1);
2007 curPos++;
2009 break;
2011 case '|': /* Pipe character only if not || */
2012 if (!inQuotes) {
2013 lastWasRedirect = FALSE;
2015 /* Add an entry to the command list */
2016 if (curStringLen > 0) {
2018 /* Add the current command */
2019 WCMD_addCommand(curString, &curStringLen,
2020 curRedirs, &curRedirsLen,
2021 &curCopyTo, &curLen,
2022 prevDelim, curDepth,
2023 &lastEntry, output);
2027 if (*(curPos+1) == '|') {
2028 curPos++; /* Skip other | */
2029 prevDelim = CMD_ONFAILURE;
2030 } else {
2031 prevDelim = CMD_PIPE;
2033 } else {
2034 curCopyTo[(*curLen)++] = *curPos;
2036 break;
2038 case '"': if (WCMD_IsEndQuote(curPos, inQuotes)) {
2039 inQuotes--;
2040 } else {
2041 inQuotes++; /* Quotes within quotes are fun! */
2043 curCopyTo[(*curLen)++] = *curPos;
2044 lastWasRedirect = FALSE;
2045 break;
2047 case '(': /* If a '(' is the first non whitespace in a command portion
2048 ie start of line or just after &&, then we read until an
2049 unquoted ) is found */
2050 WINE_TRACE("Found '(' conditions: curLen(%d), inQ(%d), onlyWS(%d)"
2051 ", for(%d, In:%d, Do:%d)"
2052 ", if(%d, else:%d, lwe:%d)\n",
2053 *curLen, inQuotes,
2054 onlyWhiteSpace,
2055 inFor, lastWasIn, lastWasDo,
2056 inIf, inElse, lastWasElse);
2057 lastWasRedirect = FALSE;
2059 /* Ignore open brackets inside the for set */
2060 if (*curLen == 0 && !inIn) {
2061 curDepth++;
2063 /* If in quotes, ignore brackets */
2064 } else if (inQuotes) {
2065 curCopyTo[(*curLen)++] = *curPos;
2067 /* In a FOR loop, an unquoted '(' may occur straight after
2068 IN or DO
2069 In an IF statement just handle it regardless as we don't
2070 parse the operands
2071 In an ELSE statement, only allow it straight away after
2072 the ELSE and whitespace
2074 } else if (inIf ||
2075 (inElse && lastWasElse && onlyWhiteSpace) ||
2076 (inFor && (lastWasIn || lastWasDo) && onlyWhiteSpace)) {
2078 /* If entering into an 'IN', set inIn */
2079 if (inFor && lastWasIn && onlyWhiteSpace) {
2080 WINE_TRACE("Inside an IN\n");
2081 inIn = TRUE;
2084 /* Add the current command */
2085 WCMD_addCommand(curString, &curStringLen,
2086 curRedirs, &curRedirsLen,
2087 &curCopyTo, &curLen,
2088 prevDelim, curDepth,
2089 &lastEntry, output);
2091 curDepth++;
2092 } else {
2093 curCopyTo[(*curLen)++] = *curPos;
2095 break;
2097 case '&': if (!inQuotes) {
2098 lastWasRedirect = FALSE;
2100 /* Add an entry to the command list */
2101 if (curStringLen > 0) {
2103 /* Add the current command */
2104 WCMD_addCommand(curString, &curStringLen,
2105 curRedirs, &curRedirsLen,
2106 &curCopyTo, &curLen,
2107 prevDelim, curDepth,
2108 &lastEntry, output);
2112 if (*(curPos+1) == '&') {
2113 curPos++; /* Skip other & */
2114 prevDelim = CMD_ONSUCCESS;
2115 } else {
2116 prevDelim = CMD_NONE;
2118 } else {
2119 curCopyTo[(*curLen)++] = *curPos;
2121 break;
2123 case ')': if (!inQuotes && curDepth > 0) {
2124 lastWasRedirect = FALSE;
2126 /* Add the current command if there is one */
2127 if (curStringLen) {
2129 /* Add the current command */
2130 WCMD_addCommand(curString, &curStringLen,
2131 curRedirs, &curRedirsLen,
2132 &curCopyTo, &curLen,
2133 prevDelim, curDepth,
2134 &lastEntry, output);
2137 /* Add an empty entry to the command list */
2138 prevDelim = CMD_NONE;
2139 WCMD_addCommand(NULL, &curStringLen,
2140 curRedirs, &curRedirsLen,
2141 &curCopyTo, &curLen,
2142 prevDelim, curDepth,
2143 &lastEntry, output);
2144 curDepth--;
2146 /* Leave inIn if necessary */
2147 if (inIn) inIn = FALSE;
2148 } else {
2149 curCopyTo[(*curLen)++] = *curPos;
2151 break;
2152 default:
2153 lastWasRedirect = FALSE;
2154 curCopyTo[(*curLen)++] = *curPos;
2157 curPos++;
2159 /* At various times we need to know if we have only skipped whitespace,
2160 so reset this variable and then it will remain true until a non
2161 whitespace is found */
2162 if ((thisChar != ' ') && (thisChar != '\t') && (thisChar != '\n'))
2163 onlyWhiteSpace = FALSE;
2165 /* Flag end of interest in FOR DO and IN parms once something has been processed */
2166 if (!lastWasWhiteSpace) {
2167 lastWasIn = lastWasDo = FALSE;
2170 /* If we have reached the end, add this command into the list */
2171 if (*curPos == 0x00 && *curLen > 0) {
2173 /* Add an entry to the command list */
2174 WCMD_addCommand(curString, &curStringLen,
2175 curRedirs, &curRedirsLen,
2176 &curCopyTo, &curLen,
2177 prevDelim, curDepth,
2178 &lastEntry, output);
2181 /* If we have reached the end of the string, see if bracketing outstanding */
2182 if (*curPos == 0x00 && curDepth > 0 && readFrom != INVALID_HANDLE_VALUE) {
2183 inRem = FALSE;
2184 prevDelim = CMD_NONE;
2185 inQuotes = 0;
2186 memset(extraSpace, 0x00, (MAXSTRING+1) * sizeof(WCHAR));
2188 /* Read more, skipping any blank lines */
2189 while (*extraSpace == 0x00) {
2190 if (!context) WCMD_output_asis( WCMD_LoadMessage(WCMD_MOREPROMPT));
2191 if (!WCMD_fgets(extraSpace, MAXSTRING, readFrom, is_console_handle))
2192 break;
2194 curPos = extraSpace;
2195 if (context) handleExpansion(extraSpace, FALSE, NULL, NULL);
2196 /* Continue to echo commands IF echo is on and in batch program */
2197 if (context && echo_mode && extraSpace[0] && (extraSpace[0] != '@')) {
2198 WCMD_output_asis(extraSpace);
2199 WCMD_output_asis(newline);
2204 /* Dump out the parsed output */
2205 WCMD_DumpCommands(*output);
2207 return extraSpace;
2210 /***************************************************************************
2211 * WCMD_process_commands
2213 * Process all the commands read in so far
2215 CMD_LIST *WCMD_process_commands(CMD_LIST *thisCmd, BOOL oneBracket,
2216 const WCHAR *var, const WCHAR *val) {
2218 int bdepth = -1;
2220 if (thisCmd && oneBracket) bdepth = thisCmd->bracketDepth;
2222 /* Loop through the commands, processing them one by one */
2223 while (thisCmd) {
2225 CMD_LIST *origCmd = thisCmd;
2227 /* If processing one bracket only, and we find the end bracket
2228 entry (or less), return */
2229 if (oneBracket && !thisCmd->command &&
2230 bdepth <= thisCmd->bracketDepth) {
2231 WINE_TRACE("Finished bracket @ %p, next command is %p\n",
2232 thisCmd, thisCmd->nextcommand);
2233 return thisCmd->nextcommand;
2236 /* Ignore the NULL entries a ')' inserts (Only 'if' cares
2237 about them and it will be handled in there)
2238 Also, skip over any batch labels (eg. :fred) */
2239 if (thisCmd->command && thisCmd->command[0] != ':') {
2240 WINE_TRACE("Executing command: '%s'\n", wine_dbgstr_w(thisCmd->command));
2241 WCMD_execute (thisCmd->command, thisCmd->redirects, var, val, &thisCmd);
2244 /* Step on unless the command itself already stepped on */
2245 if (thisCmd == origCmd) thisCmd = thisCmd->nextcommand;
2247 return NULL;
2250 /***************************************************************************
2251 * WCMD_free_commands
2253 * Frees the storage held for a parsed command line
2254 * - This is not done in the process_commands, as eventually the current
2255 * pointer will be modified within the commands, and hence a single free
2256 * routine is simpler
2258 void WCMD_free_commands(CMD_LIST *cmds) {
2260 /* Loop through the commands, freeing them one by one */
2261 while (cmds) {
2262 CMD_LIST *thisCmd = cmds;
2263 cmds = cmds->nextcommand;
2264 HeapFree(GetProcessHeap(), 0, thisCmd->command);
2265 HeapFree(GetProcessHeap(), 0, thisCmd->redirects);
2266 HeapFree(GetProcessHeap(), 0, thisCmd);
2271 /*****************************************************************************
2272 * Main entry point. This is a console application so we have a main() not a
2273 * winmain().
2276 int wmain (int argc, WCHAR *argvW[])
2278 int args;
2279 WCHAR *cmd = NULL;
2280 WCHAR string[1024];
2281 WCHAR envvar[4];
2282 int opt_q;
2283 BOOL is_console;
2284 DWORD dummy;
2285 int opt_t = 0;
2286 static const WCHAR promptW[] = {'P','R','O','M','P','T','\0'};
2287 static const WCHAR defaultpromptW[] = {'$','P','$','G','\0'};
2288 char ansiVersion[100];
2289 CMD_LIST *toExecute = NULL; /* Commands left to be executed */
2291 srand(time(NULL));
2293 /* Pre initialize some messages */
2294 strcpy(ansiVersion, PACKAGE_VERSION);
2295 MultiByteToWideChar(CP_ACP, 0, ansiVersion, -1, string, 1024);
2296 wsprintfW(version_string, WCMD_LoadMessage(WCMD_VERSION), string);
2297 strcpyW(anykey, WCMD_LoadMessage(WCMD_ANYKEY));
2299 args = argc;
2300 opt_c=opt_k=opt_q=opt_s=0;
2301 while (args > 0)
2303 WCHAR c;
2304 WINE_TRACE("Command line parm: '%s'\n", wine_dbgstr_w(*argvW));
2305 if ((*argvW)[0]!='/' || (*argvW)[1]=='\0') {
2306 argvW++;
2307 args--;
2308 continue;
2311 c=(*argvW)[1];
2312 if (tolowerW(c)=='c') {
2313 opt_c=1;
2314 } else if (tolowerW(c)=='q') {
2315 opt_q=1;
2316 } else if (tolowerW(c)=='k') {
2317 opt_k=1;
2318 } else if (tolowerW(c)=='s') {
2319 opt_s=1;
2320 } else if (tolowerW(c)=='a') {
2321 unicodePipes=FALSE;
2322 } else if (tolowerW(c)=='u') {
2323 unicodePipes=TRUE;
2324 } else if (tolowerW(c)=='t' && (*argvW)[2]==':') {
2325 opt_t=strtoulW(&(*argvW)[3], NULL, 16);
2326 } else if (tolowerW(c)=='x' || tolowerW(c)=='y') {
2327 /* Ignored for compatibility with Windows */
2330 if ((*argvW)[2]==0) {
2331 argvW++;
2332 args--;
2334 else /* handle `cmd /cnotepad.exe` and `cmd /x/c ...` */
2336 *argvW+=2;
2339 if (opt_c || opt_k) /* break out of parsing immediately after c or k */
2340 break;
2343 if (opt_q) {
2344 static const WCHAR eoff[] = {'O','F','F','\0'};
2345 WCMD_echo(eoff);
2348 if (opt_c || opt_k) {
2349 int len,qcount;
2350 WCHAR** arg;
2351 int argsLeft;
2352 WCHAR* p;
2354 /* opt_s left unflagged if the command starts with and contains exactly
2355 * one quoted string (exactly two quote characters). The quoted string
2356 * must be an executable name that has whitespace and must not have the
2357 * following characters: &<>()@^| */
2359 /* Build the command to execute */
2360 len = 0;
2361 qcount = 0;
2362 argsLeft = args;
2363 for (arg = argvW; argsLeft>0; arg++,argsLeft--)
2365 int has_space,bcount;
2366 WCHAR* a;
2368 has_space=0;
2369 bcount=0;
2370 a=*arg;
2371 if( !*a ) has_space=1;
2372 while (*a!='\0') {
2373 if (*a=='\\') {
2374 bcount++;
2375 } else {
2376 if (*a==' ' || *a=='\t') {
2377 has_space=1;
2378 } else if (*a=='"') {
2379 /* doubling of '\' preceding a '"',
2380 * plus escaping of said '"'
2382 len+=2*bcount+1;
2383 qcount++;
2385 bcount=0;
2387 a++;
2389 len+=(a-*arg) + 1; /* for the separating space */
2390 if (has_space)
2392 len+=2; /* for the quotes */
2393 qcount+=2;
2397 if (qcount!=2)
2398 opt_s=1;
2400 /* check argvW[0] for a space and invalid characters */
2401 if (!opt_s) {
2402 opt_s=1;
2403 p=*argvW;
2404 while (*p!='\0') {
2405 if (*p=='&' || *p=='<' || *p=='>' || *p=='(' || *p==')'
2406 || *p=='@' || *p=='^' || *p=='|') {
2407 opt_s=1;
2408 break;
2410 if (*p==' ')
2411 opt_s=0;
2412 p++;
2416 cmd = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
2417 if (!cmd)
2418 exit(1);
2420 p = cmd;
2421 argsLeft = args;
2422 for (arg = argvW; argsLeft>0; arg++,argsLeft--)
2424 int has_space,has_quote;
2425 WCHAR* a;
2427 /* Check for quotes and spaces in this argument */
2428 has_space=has_quote=0;
2429 a=*arg;
2430 if( !*a ) has_space=1;
2431 while (*a!='\0') {
2432 if (*a==' ' || *a=='\t') {
2433 has_space=1;
2434 if (has_quote)
2435 break;
2436 } else if (*a=='"') {
2437 has_quote=1;
2438 if (has_space)
2439 break;
2441 a++;
2444 /* Now transfer it to the command line */
2445 if (has_space)
2446 *p++='"';
2447 if (has_quote) {
2448 int bcount;
2449 WCHAR* a;
2451 bcount=0;
2452 a=*arg;
2453 while (*a!='\0') {
2454 if (*a=='\\') {
2455 *p++=*a;
2456 bcount++;
2457 } else {
2458 if (*a=='"') {
2459 int i;
2461 /* Double all the '\\' preceding this '"', plus one */
2462 for (i=0;i<=bcount;i++)
2463 *p++='\\';
2464 *p++='"';
2465 } else {
2466 *p++=*a;
2468 bcount=0;
2470 a++;
2472 } else {
2473 strcpyW(p,*arg);
2474 p+=strlenW(*arg);
2476 if (has_space)
2477 *p++='"';
2478 *p++=' ';
2480 if (p > cmd)
2481 p--; /* remove last space */
2482 *p = '\0';
2484 WINE_TRACE("/c command line: '%s'\n", wine_dbgstr_w(cmd));
2486 /* strip first and last quote characters if opt_s; check for invalid
2487 * executable is done later */
2488 if (opt_s && *cmd=='\"')
2489 WCMD_opt_s_strip_quotes(cmd);
2492 if (opt_c) {
2493 /* If we do a "cmd /c command", we don't want to allocate a new
2494 * console since the command returns immediately. Rather, we use
2495 * the currently allocated input and output handles. This allows
2496 * us to pipe to and read from the command interpreter.
2499 /* Parse the command string, without reading any more input */
2500 WCMD_ReadAndParseLine(cmd, &toExecute, INVALID_HANDLE_VALUE, FALSE);
2501 WCMD_process_commands(toExecute, FALSE, NULL, NULL);
2502 WCMD_free_commands(toExecute);
2503 toExecute = NULL;
2505 HeapFree(GetProcessHeap(), 0, cmd);
2506 return errorlevel;
2509 SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), ENABLE_LINE_INPUT |
2510 ENABLE_ECHO_INPUT | ENABLE_PROCESSED_INPUT);
2511 SetConsoleTitleW(WCMD_LoadMessage(WCMD_CONSTITLE));
2513 /* Note: cmd.exe /c dir does not get a new color, /k dir does */
2514 if (opt_t) {
2515 if (!(((opt_t & 0xF0) >> 4) == (opt_t & 0x0F))) {
2516 defaultColor = opt_t & 0xFF;
2517 param1[0] = 0x00;
2518 WCMD_color();
2520 } else {
2521 /* Check HKCU\Software\Microsoft\Command Processor
2522 Then HKLM\Software\Microsoft\Command Processor
2523 for defaultcolour value
2524 Note Can be supplied as DWORD or REG_SZ
2525 Note2 When supplied as REG_SZ it's in decimal!!! */
2526 HKEY key;
2527 DWORD type;
2528 DWORD value=0, size=4;
2529 static const WCHAR regKeyW[] = {'S','o','f','t','w','a','r','e','\\',
2530 'M','i','c','r','o','s','o','f','t','\\',
2531 'C','o','m','m','a','n','d',' ','P','r','o','c','e','s','s','o','r','\0'};
2532 static const WCHAR dfltColorW[] = {'D','e','f','a','u','l','t','C','o','l','o','r','\0'};
2534 if (RegOpenKeyExW(HKEY_CURRENT_USER, regKeyW,
2535 0, KEY_READ, &key) == ERROR_SUCCESS) {
2536 WCHAR strvalue[4];
2538 /* See if DWORD or REG_SZ */
2539 if (RegQueryValueExW(key, dfltColorW, NULL, &type,
2540 NULL, NULL) == ERROR_SUCCESS) {
2541 if (type == REG_DWORD) {
2542 size = sizeof(DWORD);
2543 RegQueryValueExW(key, dfltColorW, NULL, NULL,
2544 (LPBYTE)&value, &size);
2545 } else if (type == REG_SZ) {
2546 size = sizeof(strvalue)/sizeof(WCHAR);
2547 RegQueryValueExW(key, dfltColorW, NULL, NULL,
2548 (LPBYTE)strvalue, &size);
2549 value = strtoulW(strvalue, NULL, 10);
2552 RegCloseKey(key);
2555 if (value == 0 && RegOpenKeyExW(HKEY_LOCAL_MACHINE, regKeyW,
2556 0, KEY_READ, &key) == ERROR_SUCCESS) {
2557 WCHAR strvalue[4];
2559 /* See if DWORD or REG_SZ */
2560 if (RegQueryValueExW(key, dfltColorW, NULL, &type,
2561 NULL, NULL) == ERROR_SUCCESS) {
2562 if (type == REG_DWORD) {
2563 size = sizeof(DWORD);
2564 RegQueryValueExW(key, dfltColorW, NULL, NULL,
2565 (LPBYTE)&value, &size);
2566 } else if (type == REG_SZ) {
2567 size = sizeof(strvalue)/sizeof(WCHAR);
2568 RegQueryValueExW(key, dfltColorW, NULL, NULL,
2569 (LPBYTE)strvalue, &size);
2570 value = strtoulW(strvalue, NULL, 10);
2573 RegCloseKey(key);
2576 /* If one found, set the screen to that colour */
2577 if (!(((value & 0xF0) >> 4) == (value & 0x0F))) {
2578 defaultColor = value & 0xFF;
2579 param1[0] = 0x00;
2580 WCMD_color();
2585 /* Save cwd into appropriate env var */
2586 GetCurrentDirectoryW(1024, string);
2587 if (IsCharAlphaW(string[0]) && string[1] == ':') {
2588 static const WCHAR fmt[] = {'=','%','c',':','\0'};
2589 wsprintfW(envvar, fmt, string[0]);
2590 SetEnvironmentVariableW(envvar, string);
2591 WINE_TRACE("Set %s to %s\n", wine_dbgstr_w(envvar), wine_dbgstr_w(string));
2594 if (opt_k) {
2595 /* Parse the command string, without reading any more input */
2596 WCMD_ReadAndParseLine(cmd, &toExecute, INVALID_HANDLE_VALUE, FALSE);
2597 WCMD_process_commands(toExecute, FALSE, NULL, NULL);
2598 WCMD_free_commands(toExecute);
2599 toExecute = NULL;
2600 HeapFree(GetProcessHeap(), 0, cmd);
2604 * Loop forever getting commands and executing them.
2607 SetEnvironmentVariableW(promptW, defaultpromptW);
2608 WCMD_version ();
2609 is_console = !!GetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), &dummy);
2610 while (TRUE) {
2612 /* Read until EOF (which for std input is never, but if redirect
2613 in place, may occur */
2614 if (echo_mode) WCMD_show_prompt();
2615 if (!WCMD_ReadAndParseLine(NULL, &toExecute, GetStdHandle(STD_INPUT_HANDLE), is_console))
2616 break;
2617 WCMD_process_commands(toExecute, FALSE, NULL, NULL);
2618 WCMD_free_commands(toExecute);
2619 toExecute = NULL;
2621 return 0;