cmd: Use helper function to return file io buffer.
[wine.git] / programs / cmd / wcmdmain.c
blobb254728cb5ffa57b10c4bdeb74a80287a73b101c
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 in WCMD_output\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));
186 static int line_count;
187 static int max_height;
188 static int max_width;
189 static BOOL paged_mode;
190 static int numChars;
192 void WCMD_enter_paged_mode(const WCHAR *msg)
194 CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
196 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &consoleInfo)) {
197 max_height = consoleInfo.dwSize.Y;
198 max_width = consoleInfo.dwSize.X;
199 } else {
200 max_height = 25;
201 max_width = 80;
203 paged_mode = TRUE;
204 line_count = 0;
205 numChars = 0;
206 pagedMessage = (msg==NULL)? anykey : msg;
209 void WCMD_leave_paged_mode(void)
211 paged_mode = FALSE;
212 pagedMessage = NULL;
215 /***************************************************************************
216 * WCMD_Readfile
218 * Read characters in from a console/file, returning result in Unicode
219 * with signature identical to ReadFile
221 BOOL WCMD_ReadFile(const HANDLE hIn, WCHAR *intoBuf, const DWORD maxChars,
222 LPDWORD charsRead, const LPOVERLAPPED unused) {
224 BOOL res;
226 /* Try to read from console as Unicode */
227 res = ReadConsoleW(hIn, intoBuf, maxChars, charsRead, NULL);
229 /* If reading from console has failed we assume its file
230 i/o so read in and convert from OEM codepage */
231 if (!res) {
233 DWORD numRead;
234 char *buffer;
236 if (!(buffer = get_file_buffer()))
237 return FALSE;
239 /* Read from file (assume OEM codepage) */
240 res = ReadFile(hIn, buffer, maxChars, &numRead, unused);
242 /* Convert from OEM */
243 *charsRead = MultiByteToWideChar(GetConsoleCP(), 0, buffer, numRead,
244 intoBuf, maxChars);
247 return res;
250 /*******************************************************************
251 * WCMD_output_asis_handle
253 * Send output to specified handle without formatting e.g. when message contains '%'
255 static void WCMD_output_asis_handle (DWORD std_handle, const WCHAR *message) {
256 DWORD count;
257 const WCHAR* ptr;
258 WCHAR string[1024];
259 HANDLE handle = GetStdHandle(std_handle);
261 if (paged_mode) {
262 do {
263 ptr = message;
264 while (*ptr && *ptr!='\n' && (numChars < max_width)) {
265 numChars++;
266 ptr++;
268 if (*ptr == '\n') ptr++;
269 WCMD_output_asis_len(message, (ptr) ? ptr - message : strlenW(message), handle);
270 if (ptr) {
271 numChars = 0;
272 if (++line_count >= max_height - 1) {
273 line_count = 0;
274 WCMD_output_asis_len(pagedMessage, strlenW(pagedMessage), handle);
275 WCMD_ReadFile (GetStdHandle(STD_INPUT_HANDLE), string,
276 sizeof(string)/sizeof(WCHAR), &count, NULL);
279 } while (((message = ptr) != NULL) && (*ptr));
280 } else {
281 WCMD_output_asis_len(message, lstrlenW(message), handle);
285 /*******************************************************************
286 * WCMD_output_asis
288 * Send output to current standard output device, without formatting
289 * e.g. when message contains '%'
291 void WCMD_output_asis (const WCHAR *message) {
292 WCMD_output_asis_handle(STD_OUTPUT_HANDLE, message);
295 /*******************************************************************
296 * WCMD_output_asis_stderr
298 * Send output to current standard error device, without formatting
299 * e.g. when message contains '%'
301 void WCMD_output_asis_stderr (const WCHAR *message) {
302 WCMD_output_asis_handle(STD_ERROR_HANDLE, message);
305 /****************************************************************************
306 * WCMD_print_error
308 * Print the message for GetLastError
311 void WCMD_print_error (void) {
312 LPVOID lpMsgBuf;
313 DWORD error_code;
314 int status;
316 error_code = GetLastError ();
317 status = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
318 NULL, error_code, 0, (LPWSTR) &lpMsgBuf, 0, NULL);
319 if (!status) {
320 WINE_FIXME ("Cannot display message for error %d, status %d\n",
321 error_code, GetLastError());
322 return;
325 WCMD_output_asis_len(lpMsgBuf, lstrlenW(lpMsgBuf),
326 GetStdHandle(STD_ERROR_HANDLE));
327 LocalFree (lpMsgBuf);
328 WCMD_output_asis_len (newline, lstrlenW(newline),
329 GetStdHandle(STD_ERROR_HANDLE));
330 return;
333 /******************************************************************************
334 * WCMD_show_prompt
336 * Display the prompt on STDout
340 static void WCMD_show_prompt (void) {
342 int status;
343 WCHAR out_string[MAX_PATH], curdir[MAX_PATH], prompt_string[MAX_PATH];
344 WCHAR *p, *q;
345 DWORD len;
346 static const WCHAR envPrompt[] = {'P','R','O','M','P','T','\0'};
348 len = GetEnvironmentVariableW(envPrompt, prompt_string,
349 sizeof(prompt_string)/sizeof(WCHAR));
350 if ((len == 0) || (len >= (sizeof(prompt_string)/sizeof(WCHAR)))) {
351 static const WCHAR dfltPrompt[] = {'$','P','$','G','\0'};
352 strcpyW (prompt_string, dfltPrompt);
354 p = prompt_string;
355 q = out_string;
356 *q++ = '\r';
357 *q++ = '\n';
358 *q = '\0';
359 while (*p != '\0') {
360 if (*p != '$') {
361 *q++ = *p++;
362 *q = '\0';
364 else {
365 p++;
366 switch (toupper(*p)) {
367 case '$':
368 *q++ = '$';
369 break;
370 case 'A':
371 *q++ = '&';
372 break;
373 case 'B':
374 *q++ = '|';
375 break;
376 case 'C':
377 *q++ = '(';
378 break;
379 case 'D':
380 GetDateFormatW(LOCALE_USER_DEFAULT, DATE_SHORTDATE, NULL, NULL, q, MAX_PATH);
381 while (*q) q++;
382 break;
383 case 'E':
384 *q++ = '\E';
385 break;
386 case 'F':
387 *q++ = ')';
388 break;
389 case 'G':
390 *q++ = '>';
391 break;
392 case 'H':
393 *q++ = '\b';
394 break;
395 case 'L':
396 *q++ = '<';
397 break;
398 case 'N':
399 status = GetCurrentDirectoryW(sizeof(curdir)/sizeof(WCHAR), curdir);
400 if (status) {
401 *q++ = curdir[0];
403 break;
404 case 'P':
405 status = GetCurrentDirectoryW(sizeof(curdir)/sizeof(WCHAR), curdir);
406 if (status) {
407 strcatW (q, curdir);
408 while (*q) q++;
410 break;
411 case 'Q':
412 *q++ = '=';
413 break;
414 case 'S':
415 *q++ = ' ';
416 break;
417 case 'T':
418 GetTimeFormatW(LOCALE_USER_DEFAULT, 0, NULL, NULL, q, MAX_PATH);
419 while (*q) q++;
420 break;
421 case 'V':
422 strcatW (q, version_string);
423 while (*q) q++;
424 break;
425 case '_':
426 *q++ = '\n';
427 break;
428 case '+':
429 if (pushd_directories) {
430 memset(q, '+', pushd_directories->u.stackdepth);
431 q = q + pushd_directories->u.stackdepth;
433 break;
435 p++;
436 *q = '\0';
439 WCMD_output_asis (out_string);
443 /*************************************************************************
444 * WCMD_strdupW
445 * A wide version of strdup as its missing from unicode.h
447 WCHAR *WCMD_strdupW(const WCHAR *input) {
448 int len=strlenW(input)+1;
449 WCHAR *result = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
450 memcpy(result, input, len * sizeof(WCHAR));
451 return result;
454 /*************************************************************************
455 * WCMD_strsubstW
456 * Replaces a portion of a Unicode string with the specified string.
457 * It's up to the caller to ensure there is enough space in the
458 * destination buffer.
460 void WCMD_strsubstW(WCHAR *start, const WCHAR *next, const WCHAR *insert, int len) {
462 if (len < 0)
463 len=insert ? lstrlenW(insert) : 0;
464 if (start+len != next)
465 memmove(start+len, next, (strlenW(next) + 1) * sizeof(*next));
466 if (insert)
467 memcpy(start, insert, len * sizeof(*insert));
470 /***************************************************************************
471 * WCMD_skip_leading_spaces
473 * Return a pointer to the first non-whitespace character of string.
474 * Does not modify the input string.
476 WCHAR *WCMD_skip_leading_spaces (WCHAR *string) {
478 WCHAR *ptr;
480 ptr = string;
481 while (*ptr == ' ' || *ptr == '\t') ptr++;
482 return ptr;
485 /***************************************************************************
486 * WCMD_keyword_ws_found
488 * Checks if the string located at ptr matches a keyword (of length len)
489 * followed by a whitespace character (space or tab)
491 BOOL WCMD_keyword_ws_found(const WCHAR *keyword, int len, const WCHAR *ptr) {
492 return (CompareStringW(LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
493 ptr, len, keyword, len) == CSTR_EQUAL)
494 && ((*(ptr + len) == ' ') || (*(ptr + len) == '\t'));
497 /*************************************************************************
498 * WCMD_opt_s_strip_quotes
500 * Remove first and last quote WCHARacters, preserving all other text
502 void WCMD_opt_s_strip_quotes(WCHAR *cmd) {
503 WCHAR *src = cmd + 1, *dest = cmd, *lastq = NULL;
504 while((*dest=*src) != '\0') {
505 if (*src=='\"')
506 lastq=dest;
507 dest++, src++;
509 if (lastq) {
510 dest=lastq++;
511 while ((*dest++=*lastq++) != 0)
517 /*************************************************************************
518 * WCMD_is_magic_envvar
519 * Return TRUE if s is '%'magicvar'%'
520 * and is not masked by a real environment variable.
523 static inline BOOL WCMD_is_magic_envvar(const WCHAR *s, const WCHAR *magicvar)
525 int len;
527 if (s[0] != '%')
528 return FALSE; /* Didn't begin with % */
529 len = strlenW(s);
530 if (len < 2 || s[len-1] != '%')
531 return FALSE; /* Didn't end with another % */
533 if (CompareStringW(LOCALE_USER_DEFAULT,
534 NORM_IGNORECASE | SORT_STRINGSORT,
535 s+1, len-2, magicvar, -1) != CSTR_EQUAL) {
536 /* Name doesn't match. */
537 return FALSE;
540 if (GetEnvironmentVariableW(magicvar, NULL, 0) > 0) {
541 /* Masked by real environment variable. */
542 return FALSE;
545 return TRUE;
548 /*************************************************************************
549 * WCMD_expand_envvar
551 * Expands environment variables, allowing for WCHARacter substitution
553 static WCHAR *WCMD_expand_envvar(WCHAR *start,
554 const WCHAR *forVar, const WCHAR *forVal) {
555 WCHAR *endOfVar = NULL, *s;
556 WCHAR *colonpos = NULL;
557 WCHAR thisVar[MAXSTRING];
558 WCHAR thisVarContents[MAXSTRING];
559 WCHAR savedchar = 0x00;
560 int len;
562 static const WCHAR ErrorLvl[] = {'E','R','R','O','R','L','E','V','E','L','\0'};
563 static const WCHAR Date[] = {'D','A','T','E','\0'};
564 static const WCHAR Time[] = {'T','I','M','E','\0'};
565 static const WCHAR Cd[] = {'C','D','\0'};
566 static const WCHAR Random[] = {'R','A','N','D','O','M','\0'};
567 static const WCHAR Delims[] = {'%',' ',':','\0'};
569 WINE_TRACE("Expanding: %s (%s,%s)\n", wine_dbgstr_w(start),
570 wine_dbgstr_w(forVal), wine_dbgstr_w(forVar));
572 /* Find the end of the environment variable, and extract name */
573 endOfVar = strpbrkW(start+1, Delims);
575 if (endOfVar == NULL || *endOfVar==' ') {
577 /* In batch program, missing terminator for % and no following
578 ':' just removes the '%' */
579 if (context) {
580 WCMD_strsubstW(start, start + 1, NULL, 0);
581 return start;
582 } else {
584 /* In command processing, just ignore it - allows command line
585 syntax like: for %i in (a.a) do echo %i */
586 return start+1;
590 /* If ':' found, process remaining up until '%' (or stop at ':' if
591 a missing '%' */
592 if (*endOfVar==':') {
593 WCHAR *endOfVar2 = strchrW(endOfVar+1, '%');
594 if (endOfVar2 != NULL) endOfVar = endOfVar2;
597 memcpy(thisVar, start, ((endOfVar - start) + 1) * sizeof(WCHAR));
598 thisVar[(endOfVar - start)+1] = 0x00;
599 colonpos = strchrW(thisVar+1, ':');
601 /* If there's complex substitution, just need %var% for now
602 to get the expanded data to play with */
603 if (colonpos) {
604 *colonpos = '%';
605 savedchar = *(colonpos+1);
606 *(colonpos+1) = 0x00;
609 WINE_TRACE("Retrieving contents of %s\n", wine_dbgstr_w(thisVar));
611 /* Expand to contents, if unchanged, return */
612 /* Handle DATE, TIME, ERRORLEVEL and CD replacements allowing */
613 /* override if existing env var called that name */
614 if (WCMD_is_magic_envvar(thisVar, ErrorLvl)) {
615 static const WCHAR fmt[] = {'%','d','\0'};
616 wsprintfW(thisVarContents, fmt, errorlevel);
617 len = strlenW(thisVarContents);
618 } else if (WCMD_is_magic_envvar(thisVar, Date)) {
619 GetDateFormatW(LOCALE_USER_DEFAULT, DATE_SHORTDATE, NULL,
620 NULL, thisVarContents, MAXSTRING);
621 len = strlenW(thisVarContents);
622 } else if (WCMD_is_magic_envvar(thisVar, Time)) {
623 GetTimeFormatW(LOCALE_USER_DEFAULT, TIME_NOSECONDS, NULL,
624 NULL, thisVarContents, MAXSTRING);
625 len = strlenW(thisVarContents);
626 } else if (WCMD_is_magic_envvar(thisVar, Cd)) {
627 GetCurrentDirectoryW(MAXSTRING, thisVarContents);
628 len = strlenW(thisVarContents);
629 } else if (WCMD_is_magic_envvar(thisVar, Random)) {
630 static const WCHAR fmt[] = {'%','d','\0'};
631 wsprintfW(thisVarContents, fmt, rand() % 32768);
632 len = strlenW(thisVarContents);
634 /* Look for a matching 'for' variable */
635 } else if (forVar &&
636 (CompareStringW(LOCALE_USER_DEFAULT,
637 SORT_STRINGSORT,
638 thisVar,
639 (colonpos - thisVar) - 1,
640 forVar, -1) == CSTR_EQUAL)) {
641 strcpyW(thisVarContents, forVal);
642 len = strlenW(thisVarContents);
644 } else {
646 len = ExpandEnvironmentStringsW(thisVar, thisVarContents,
647 sizeof(thisVarContents)/sizeof(WCHAR));
650 if (len == 0)
651 return endOfVar+1;
653 /* In a batch program, unknown env vars are replaced with nothing,
654 note syntax %garbage:1,3% results in anything after the ':'
655 except the %
656 From the command line, you just get back what you entered */
657 if (lstrcmpiW(thisVar, thisVarContents) == 0) {
659 /* Restore the complex part after the compare */
660 if (colonpos) {
661 *colonpos = ':';
662 *(colonpos+1) = savedchar;
665 /* Command line - just ignore this */
666 if (context == NULL) return endOfVar+1;
669 /* Batch - replace unknown env var with nothing */
670 if (colonpos == NULL) {
671 WCMD_strsubstW(start, endOfVar + 1, NULL, 0);
672 } else {
673 len = strlenW(thisVar);
674 thisVar[len-1] = 0x00;
675 /* If %:...% supplied, : is retained */
676 if (colonpos == thisVar+1) {
677 WCMD_strsubstW(start, endOfVar + 1, colonpos, -1);
678 } else {
679 WCMD_strsubstW(start, endOfVar + 1, colonpos + 1, -1);
682 return start;
686 /* See if we need to do complex substitution (any ':'s), if not
687 then our work here is done */
688 if (colonpos == NULL) {
689 WCMD_strsubstW(start, endOfVar + 1, thisVarContents, -1);
690 return start;
693 /* Restore complex bit */
694 *colonpos = ':';
695 *(colonpos+1) = savedchar;
698 Handle complex substitutions:
699 xxx=yyy (replace xxx with yyy)
700 *xxx=yyy (replace up to and including xxx with yyy)
701 ~x (from x WCHARs in)
702 ~-x (from x WCHARs from the end)
703 ~x,y (from x WCHARs in for y WCHARacters)
704 ~x,-y (from x WCHARs in until y WCHARacters from the end)
707 /* ~ is substring manipulation */
708 if (savedchar == '~') {
710 int substrposition, substrlength = 0;
711 WCHAR *commapos = strchrW(colonpos+2, ',');
712 WCHAR *startCopy;
714 substrposition = atolW(colonpos+2);
715 if (commapos) substrlength = atolW(commapos+1);
717 /* Check bounds */
718 if (substrposition >= 0) {
719 startCopy = &thisVarContents[min(substrposition, len)];
720 } else {
721 startCopy = &thisVarContents[max(0, len+substrposition-1)];
724 if (commapos == NULL) {
725 /* Copy the lot */
726 WCMD_strsubstW(start, endOfVar + 1, startCopy, -1);
727 } else if (substrlength < 0) {
729 int copybytes = (len+substrlength-1)-(startCopy-thisVarContents);
730 if (copybytes > len) copybytes = len;
731 else if (copybytes < 0) copybytes = 0;
732 WCMD_strsubstW(start, endOfVar + 1, startCopy, copybytes);
733 } else {
734 WCMD_strsubstW(start, endOfVar + 1, startCopy, substrlength);
737 return start;
739 /* search and replace manipulation */
740 } else {
741 WCHAR *equalspos = strstrW(colonpos, equalsW);
742 WCHAR *replacewith = equalspos+1;
743 WCHAR *found = NULL;
744 WCHAR *searchIn;
745 WCHAR *searchFor;
747 if (equalspos == NULL) return start+1;
748 s = WCMD_strdupW(endOfVar + 1);
750 /* Null terminate both strings */
751 thisVar[strlenW(thisVar)-1] = 0x00;
752 *equalspos = 0x00;
754 /* Since we need to be case insensitive, copy the 2 buffers */
755 searchIn = WCMD_strdupW(thisVarContents);
756 CharUpperBuffW(searchIn, strlenW(thisVarContents));
757 searchFor = WCMD_strdupW(colonpos+1);
758 CharUpperBuffW(searchFor, strlenW(colonpos+1));
760 /* Handle wildcard case */
761 if (*(colonpos+1) == '*') {
762 /* Search for string to replace */
763 found = strstrW(searchIn, searchFor+1);
765 if (found) {
766 /* Do replacement */
767 strcpyW(start, replacewith);
768 strcatW(start, thisVarContents + (found-searchIn) + strlenW(searchFor+1));
769 strcatW(start, s);
770 } else {
771 /* Copy as is */
772 strcpyW(start, thisVarContents);
773 strcatW(start, s);
776 } else {
777 /* Loop replacing all instances */
778 WCHAR *lastFound = searchIn;
779 WCHAR *outputposn = start;
781 *start = 0x00;
782 while ((found = strstrW(lastFound, searchFor))) {
783 lstrcpynW(outputposn,
784 thisVarContents + (lastFound-searchIn),
785 (found - lastFound)+1);
786 outputposn = outputposn + (found - lastFound);
787 strcatW(outputposn, replacewith);
788 outputposn = outputposn + strlenW(replacewith);
789 lastFound = found + strlenW(searchFor);
791 strcatW(outputposn,
792 thisVarContents + (lastFound-searchIn));
793 strcatW(outputposn, s);
795 HeapFree(GetProcessHeap(), 0, s);
796 HeapFree(GetProcessHeap(), 0, searchIn);
797 HeapFree(GetProcessHeap(), 0, searchFor);
798 return start;
800 return start+1;
803 /*****************************************************************************
804 * Expand the command. Native expands lines from batch programs as they are
805 * read in and not again, except for 'for' variable substitution.
806 * eg. As evidence, "echo %1 && shift && echo %1" or "echo %%path%%"
808 static void handleExpansion(WCHAR *cmd, BOOL justFors,
809 const WCHAR *forVariable, const WCHAR *forValue) {
811 /* For commands in a context (batch program): */
812 /* Expand environment variables in a batch file %{0-9} first */
813 /* including support for any ~ modifiers */
814 /* Additionally: */
815 /* Expand the DATE, TIME, CD, RANDOM and ERRORLEVEL special */
816 /* names allowing environment variable overrides */
817 /* NOTE: To support the %PATH:xxx% syntax, also perform */
818 /* manual expansion of environment variables here */
820 WCHAR *p = cmd;
821 WCHAR *t;
822 int i;
824 while ((p = strchrW(p, '%'))) {
826 WINE_TRACE("Translate command:%s %d (at: %s)\n",
827 wine_dbgstr_w(cmd), justFors, wine_dbgstr_w(p));
828 i = *(p+1) - '0';
830 /* Don't touch %% unless its in Batch */
831 if (!justFors && *(p+1) == '%') {
832 if (context) {
833 WCMD_strsubstW(p, p+1, NULL, 0);
835 p+=1;
837 /* Replace %~ modifications if in batch program */
838 } else if (*(p+1) == '~') {
839 WCMD_HandleTildaModifiers(&p, forVariable, forValue, justFors);
840 p++;
842 /* Replace use of %0...%9 if in batch program*/
843 } else if (!justFors && context && (i >= 0) && (i <= 9)) {
844 t = WCMD_parameter(context -> command, i + context -> shift_count[i], NULL, NULL);
845 WCMD_strsubstW(p, p+2, t, -1);
847 /* Replace use of %* if in batch program*/
848 } else if (!justFors && context && *(p+1)=='*') {
849 WCHAR *startOfParms = NULL;
850 t = WCMD_parameter(context -> command, 1, &startOfParms, NULL);
851 if (startOfParms != NULL)
852 WCMD_strsubstW(p, p+2, startOfParms, -1);
853 else
854 WCMD_strsubstW(p, p+2, NULL, 0);
856 } else if (forVariable &&
857 (CompareStringW(LOCALE_USER_DEFAULT,
858 SORT_STRINGSORT,
860 strlenW(forVariable),
861 forVariable, -1) == CSTR_EQUAL)) {
862 WCMD_strsubstW(p, p + strlenW(forVariable), forValue, -1);
864 } else if (!justFors) {
865 p = WCMD_expand_envvar(p, forVariable, forValue);
867 /* In a FOR loop, see if this is the variable to replace */
868 } else { /* Ignore %'s on second pass of batch program */
869 p++;
873 return;
877 /*******************************************************************
878 * WCMD_parse - parse a command into parameters and qualifiers.
880 * On exit, all qualifiers are concatenated into q, the first string
881 * not beginning with "/" is in p1 and the
882 * second in p2. Any subsequent non-qualifier strings are lost.
883 * Parameters in quotes are handled.
885 static void WCMD_parse (const WCHAR *s, WCHAR *q, WCHAR *p1, WCHAR *p2)
887 int p = 0;
889 *q = *p1 = *p2 = '\0';
890 while (TRUE) {
891 switch (*s) {
892 case '/':
893 *q++ = *s++;
894 while ((*s != '\0') && (*s != ' ') && *s != '/') {
895 *q++ = toupperW (*s++);
897 *q = '\0';
898 break;
899 case ' ':
900 case '\t':
901 s++;
902 break;
903 case '"':
904 s++;
905 while ((*s != '\0') && (*s != '"')) {
906 if (p == 0) *p1++ = *s++;
907 else if (p == 1) *p2++ = *s++;
908 else s++;
910 if (p == 0) *p1 = '\0';
911 if (p == 1) *p2 = '\0';
912 p++;
913 if (*s == '"') s++;
914 break;
915 case '\0':
916 return;
917 default:
918 while ((*s != '\0') && (*s != ' ') && (*s != '\t')
919 && (*s != '=') && (*s != ',') ) {
920 if (p == 0) *p1++ = *s++;
921 else if (p == 1) *p2++ = *s++;
922 else s++;
924 /* Skip concurrent parms */
925 while ((*s == ' ') || (*s == '\t') || (*s == '=') || (*s == ',') ) s++;
927 if (p == 0) *p1 = '\0';
928 if (p == 1) *p2 = '\0';
929 p++;
934 static void init_msvcrt_io_block(STARTUPINFOW* st)
936 STARTUPINFOW st_p;
937 /* fetch the parent MSVCRT info block if any, so that the child can use the
938 * same handles as its grand-father
940 st_p.cb = sizeof(STARTUPINFOW);
941 GetStartupInfoW(&st_p);
942 st->cbReserved2 = st_p.cbReserved2;
943 st->lpReserved2 = st_p.lpReserved2;
944 if (st_p.cbReserved2 && st_p.lpReserved2)
946 /* Override the entries for fd 0,1,2 if we happened
947 * to change those std handles (this depends on the way cmd sets
948 * its new input & output handles)
950 size_t sz = max(sizeof(unsigned) + (sizeof(char) + sizeof(HANDLE)) * 3, st_p.cbReserved2);
951 BYTE* ptr = HeapAlloc(GetProcessHeap(), 0, sz);
952 if (ptr)
954 unsigned num = *(unsigned*)st_p.lpReserved2;
955 char* flags = (char*)(ptr + sizeof(unsigned));
956 HANDLE* handles = (HANDLE*)(flags + num * sizeof(char));
958 memcpy(ptr, st_p.lpReserved2, st_p.cbReserved2);
959 st->cbReserved2 = sz;
960 st->lpReserved2 = ptr;
962 #define WX_OPEN 0x01 /* see dlls/msvcrt/file.c */
963 if (num <= 0 || (flags[0] & WX_OPEN))
965 handles[0] = GetStdHandle(STD_INPUT_HANDLE);
966 flags[0] |= WX_OPEN;
968 if (num <= 1 || (flags[1] & WX_OPEN))
970 handles[1] = GetStdHandle(STD_OUTPUT_HANDLE);
971 flags[1] |= WX_OPEN;
973 if (num <= 2 || (flags[2] & WX_OPEN))
975 handles[2] = GetStdHandle(STD_ERROR_HANDLE);
976 flags[2] |= WX_OPEN;
978 #undef WX_OPEN
983 /******************************************************************************
984 * WCMD_run_program
986 * Execute a command line as an external program. Must allow recursion.
988 * Precedence:
989 * Manual testing under windows shows PATHEXT plays a key part in this,
990 * and the search algorithm and precedence appears to be as follows.
992 * Search locations:
993 * If directory supplied on command, just use that directory
994 * If extension supplied on command, look for that explicit name first
995 * Otherwise, search in each directory on the path
996 * Precedence:
997 * If extension supplied on command, look for that explicit name first
998 * Then look for supplied name .* (even if extension supplied, so
999 * 'garbage.exe' will match 'garbage.exe.cmd')
1000 * If any found, cycle through PATHEXT looking for name.exe one by one
1001 * Launching
1002 * Once a match has been found, it is launched - Code currently uses
1003 * findexecutable to achieve this which is left untouched.
1006 void WCMD_run_program (WCHAR *command, int called) {
1008 WCHAR temp[MAX_PATH];
1009 WCHAR pathtosearch[MAXSTRING];
1010 WCHAR *pathposn;
1011 WCHAR stemofsearch[MAX_PATH]; /* maximum allowed executable name is
1012 MAX_PATH, including null character */
1013 WCHAR *lastSlash;
1014 WCHAR pathext[MAXSTRING];
1015 BOOL extensionsupplied = FALSE;
1016 BOOL launched = FALSE;
1017 BOOL status;
1018 BOOL assumeInternal = FALSE;
1019 DWORD len;
1020 static const WCHAR envPath[] = {'P','A','T','H','\0'};
1021 static const WCHAR envPathExt[] = {'P','A','T','H','E','X','T','\0'};
1022 static const WCHAR delims[] = {'/','\\',':','\0'};
1024 WCMD_parse (command, quals, param1, param2); /* Quick way to get the filename */
1025 if (!(*param1) && !(*param2))
1026 return;
1028 /* Calculate the search path and stem to search for */
1029 if (strpbrkW (param1, delims) == NULL) { /* No explicit path given, search path */
1030 static const WCHAR curDir[] = {'.',';','\0'};
1031 strcpyW(pathtosearch, curDir);
1032 len = GetEnvironmentVariableW(envPath, &pathtosearch[2], (sizeof(pathtosearch)/sizeof(WCHAR))-2);
1033 if ((len == 0) || (len >= (sizeof(pathtosearch)/sizeof(WCHAR)) - 2)) {
1034 static const WCHAR curDir[] = {'.','\0'};
1035 strcpyW (pathtosearch, curDir);
1037 if (strchrW(param1, '.') != NULL) extensionsupplied = TRUE;
1038 if (strlenW(param1) >= MAX_PATH)
1040 WCMD_output_asis(WCMD_LoadMessage(WCMD_LINETOOLONG));
1041 return;
1044 strcpyW(stemofsearch, param1);
1046 } else {
1048 /* Convert eg. ..\fred to include a directory by removing file part */
1049 GetFullPathNameW(param1, sizeof(pathtosearch)/sizeof(WCHAR), pathtosearch, NULL);
1050 lastSlash = strrchrW(pathtosearch, '\\');
1051 if (lastSlash && strchrW(lastSlash, '.') != NULL) extensionsupplied = TRUE;
1052 strcpyW(stemofsearch, lastSlash+1);
1054 /* Reduce pathtosearch to a path with trailing '\' to support c:\a.bat and
1055 c:\windows\a.bat syntax */
1056 if (lastSlash) *(lastSlash + 1) = 0x00;
1059 /* Now extract PATHEXT */
1060 len = GetEnvironmentVariableW(envPathExt, pathext, sizeof(pathext)/sizeof(WCHAR));
1061 if ((len == 0) || (len >= (sizeof(pathext)/sizeof(WCHAR)))) {
1062 static const WCHAR dfltPathExt[] = {'.','b','a','t',';',
1063 '.','c','o','m',';',
1064 '.','c','m','d',';',
1065 '.','e','x','e','\0'};
1066 strcpyW (pathext, dfltPathExt);
1069 /* Loop through the search path, dir by dir */
1070 pathposn = pathtosearch;
1071 WINE_TRACE("Searching in '%s' for '%s'\n", wine_dbgstr_w(pathtosearch),
1072 wine_dbgstr_w(stemofsearch));
1073 while (!launched && pathposn) {
1075 WCHAR thisDir[MAX_PATH] = {'\0'};
1076 WCHAR *pos = NULL;
1077 BOOL found = FALSE;
1078 static const WCHAR slashW[] = {'\\','\0'};
1080 /* Work on the first directory on the search path */
1081 pos = strchrW(pathposn, ';');
1082 if (pos) {
1083 memcpy(thisDir, pathposn, (pos-pathposn) * sizeof(WCHAR));
1084 thisDir[(pos-pathposn)] = 0x00;
1085 pathposn = pos+1;
1087 } else {
1088 strcpyW(thisDir, pathposn);
1089 pathposn = NULL;
1092 /* Since you can have eg. ..\.. on the path, need to expand
1093 to full information */
1094 strcpyW(temp, thisDir);
1095 GetFullPathNameW(temp, MAX_PATH, thisDir, NULL);
1097 /* 1. If extension supplied, see if that file exists */
1098 strcatW(thisDir, slashW);
1099 strcatW(thisDir, stemofsearch);
1100 pos = &thisDir[strlenW(thisDir)]; /* Pos = end of name */
1102 /* 1. If extension supplied, see if that file exists */
1103 if (extensionsupplied) {
1104 if (GetFileAttributesW(thisDir) != INVALID_FILE_ATTRIBUTES) {
1105 found = TRUE;
1109 /* 2. Any .* matches? */
1110 if (!found) {
1111 HANDLE h;
1112 WIN32_FIND_DATAW finddata;
1113 static const WCHAR allFiles[] = {'.','*','\0'};
1115 strcatW(thisDir,allFiles);
1116 h = FindFirstFileW(thisDir, &finddata);
1117 FindClose(h);
1118 if (h != INVALID_HANDLE_VALUE) {
1120 WCHAR *thisExt = pathext;
1122 /* 3. Yes - Try each path ext */
1123 while (thisExt) {
1124 WCHAR *nextExt = strchrW(thisExt, ';');
1126 if (nextExt) {
1127 memcpy(pos, thisExt, (nextExt-thisExt) * sizeof(WCHAR));
1128 pos[(nextExt-thisExt)] = 0x00;
1129 thisExt = nextExt+1;
1130 } else {
1131 strcpyW(pos, thisExt);
1132 thisExt = NULL;
1135 if (GetFileAttributesW(thisDir) != INVALID_FILE_ATTRIBUTES) {
1136 found = TRUE;
1137 thisExt = NULL;
1143 /* Internal programs won't be picked up by this search, so even
1144 though not found, try one last createprocess and wait for it
1145 to complete.
1146 Note: Ideally we could tell between a console app (wait) and a
1147 windows app, but the API's for it fail in this case */
1148 if (!found && pathposn == NULL) {
1149 WINE_TRACE("ASSUMING INTERNAL\n");
1150 assumeInternal = TRUE;
1151 } else {
1152 WINE_TRACE("Found as %s\n", wine_dbgstr_w(thisDir));
1155 /* Once found, launch it */
1156 if (found || assumeInternal) {
1157 STARTUPINFOW st;
1158 PROCESS_INFORMATION pe;
1159 SHFILEINFOW psfi;
1160 DWORD console;
1161 HINSTANCE hinst;
1162 WCHAR *ext = strrchrW( thisDir, '.' );
1163 static const WCHAR batExt[] = {'.','b','a','t','\0'};
1164 static const WCHAR cmdExt[] = {'.','c','m','d','\0'};
1166 launched = TRUE;
1168 /* Special case BAT and CMD */
1169 if (ext && !strcmpiW(ext, batExt)) {
1170 WCMD_batch (thisDir, command, called, NULL, INVALID_HANDLE_VALUE);
1171 return;
1172 } else if (ext && !strcmpiW(ext, cmdExt)) {
1173 WCMD_batch (thisDir, command, called, NULL, INVALID_HANDLE_VALUE);
1174 return;
1175 } else {
1177 /* thisDir contains the file to be launched, but with what?
1178 eg. a.exe will require a.exe to be launched, a.html may be iexplore */
1179 hinst = FindExecutableW (thisDir, NULL, temp);
1180 if ((INT_PTR)hinst < 32)
1181 console = 0;
1182 else
1183 console = SHGetFileInfoW(temp, 0, &psfi, sizeof(psfi), SHGFI_EXETYPE);
1185 ZeroMemory (&st, sizeof(STARTUPINFOW));
1186 st.cb = sizeof(STARTUPINFOW);
1187 init_msvcrt_io_block(&st);
1189 /* Launch the process and if a CUI wait on it to complete
1190 Note: Launching internal wine processes cannot specify a full path to exe */
1191 status = CreateProcessW(assumeInternal?NULL : thisDir,
1192 command, NULL, NULL, TRUE, 0, NULL, NULL, &st, &pe);
1193 if ((opt_c || opt_k) && !opt_s && !status
1194 && GetLastError()==ERROR_FILE_NOT_FOUND && command[0]=='\"') {
1195 /* strip first and last quote WCHARacters and try again */
1196 WCMD_opt_s_strip_quotes(command);
1197 opt_s=1;
1198 WCMD_run_program(command, called);
1199 return;
1202 if (!status)
1203 break;
1205 if (!assumeInternal && !console) errorlevel = 0;
1206 else
1208 /* Always wait when called in a batch program context */
1209 if (assumeInternal || context || !HIWORD(console)) WaitForSingleObject (pe.hProcess, INFINITE);
1210 GetExitCodeProcess (pe.hProcess, &errorlevel);
1211 if (errorlevel == STILL_ACTIVE) errorlevel = 0;
1213 CloseHandle(pe.hProcess);
1214 CloseHandle(pe.hThread);
1215 return;
1220 /* Not found anywhere - give up */
1221 SetLastError(ERROR_FILE_NOT_FOUND);
1222 WCMD_print_error ();
1224 /* If a command fails to launch, it sets errorlevel 9009 - which
1225 does not seem to have any associated constant definition */
1226 errorlevel = 9009;
1227 return;
1231 /*****************************************************************************
1232 * Process one command. If the command is EXIT this routine does not return.
1233 * We will recurse through here executing batch files.
1235 void WCMD_execute (const WCHAR *command, const WCHAR *redirects,
1236 const WCHAR *forVariable, const WCHAR *forValue,
1237 CMD_LIST **cmdList)
1239 WCHAR *cmd, *p, *redir;
1240 int status, i;
1241 DWORD count, creationDisposition;
1242 HANDLE h;
1243 WCHAR *whichcmd;
1244 SECURITY_ATTRIBUTES sa;
1245 WCHAR *new_cmd = NULL;
1246 WCHAR *new_redir = NULL;
1247 HANDLE old_stdhandles[3] = {GetStdHandle (STD_INPUT_HANDLE),
1248 GetStdHandle (STD_OUTPUT_HANDLE),
1249 GetStdHandle (STD_ERROR_HANDLE)};
1250 DWORD idx_stdhandles[3] = {STD_INPUT_HANDLE,
1251 STD_OUTPUT_HANDLE,
1252 STD_ERROR_HANDLE};
1253 BOOL prev_echo_mode, piped = FALSE;
1255 WINE_TRACE("command on entry:%s (%p), with forVariable '%s'='%s'\n",
1256 wine_dbgstr_w(command), cmdList,
1257 wine_dbgstr_w(forVariable), wine_dbgstr_w(forValue));
1259 /* If the next command is a pipe then we implement pipes by redirecting
1260 the output from this command to a temp file and input into the
1261 next command from that temp file.
1262 FIXME: Use of named pipes would make more sense here as currently this
1263 process has to finish before the next one can start but this requires
1264 a change to not wait for the first app to finish but rather the pipe */
1265 if (cmdList && (*cmdList)->nextcommand &&
1266 (*cmdList)->nextcommand->prevDelim == CMD_PIPE) {
1268 WCHAR temp_path[MAX_PATH];
1269 static const WCHAR cmdW[] = {'C','M','D','\0'};
1271 /* Remember piping is in action */
1272 WINE_TRACE("Output needs to be piped\n");
1273 piped = TRUE;
1275 /* Generate a unique temporary filename */
1276 GetTempPathW(sizeof(temp_path)/sizeof(WCHAR), temp_path);
1277 GetTempFileNameW(temp_path, cmdW, 0, (*cmdList)->nextcommand->pipeFile);
1278 WINE_TRACE("Using temporary file of %s\n",
1279 wine_dbgstr_w((*cmdList)->nextcommand->pipeFile));
1282 /* Move copy of the command onto the heap so it can be expanded */
1283 new_cmd = HeapAlloc( GetProcessHeap(), 0, MAXSTRING * sizeof(WCHAR));
1284 if (!new_cmd)
1286 WINE_ERR("Could not allocate memory for new_cmd\n");
1287 return;
1289 strcpyW(new_cmd, command);
1291 /* Move copy of the redirects onto the heap so it can be expanded */
1292 new_redir = HeapAlloc( GetProcessHeap(), 0, MAXSTRING * sizeof(WCHAR));
1293 if (!new_redir)
1295 WINE_ERR("Could not allocate memory for new_redir\n");
1296 HeapFree( GetProcessHeap(), 0, new_cmd );
1297 return;
1300 /* If piped output, send stdout to the pipe by appending >filename to redirects */
1301 if (piped) {
1302 static const WCHAR redirOut[] = {'%','s',' ','>',' ','%','s','\0'};
1303 wsprintfW (new_redir, redirOut, redirects, (*cmdList)->nextcommand->pipeFile);
1304 WINE_TRACE("Redirects now %s\n", wine_dbgstr_w(new_redir));
1305 } else {
1306 strcpyW(new_redir, redirects);
1309 /* Expand variables in command line mode only (batch mode will
1310 be expanded as the line is read in, except for 'for' loops) */
1311 handleExpansion(new_cmd, (context != NULL), forVariable, forValue);
1312 handleExpansion(new_redir, (context != NULL), forVariable, forValue);
1313 cmd = new_cmd;
1316 * Changing default drive has to be handled as a special case.
1319 if ((cmd[1] == ':') && IsCharAlphaW(cmd[0]) && (strlenW(cmd) == 2)) {
1320 WCHAR envvar[5];
1321 WCHAR dir[MAX_PATH];
1323 /* According to MSDN CreateProcess docs, special env vars record
1324 the current directory on each drive, in the form =C:
1325 so see if one specified, and if so go back to it */
1326 strcpyW(envvar, equalsW);
1327 strcatW(envvar, cmd);
1328 if (GetEnvironmentVariableW(envvar, dir, MAX_PATH) == 0) {
1329 static const WCHAR fmt[] = {'%','s','\\','\0'};
1330 wsprintfW(cmd, fmt, cmd);
1331 WINE_TRACE("No special directory settings, using dir of %s\n", wine_dbgstr_w(cmd));
1333 WINE_TRACE("Got directory %s as %s\n", wine_dbgstr_w(envvar), wine_dbgstr_w(cmd));
1334 status = SetCurrentDirectoryW(cmd);
1335 if (!status) WCMD_print_error ();
1336 HeapFree( GetProcessHeap(), 0, cmd );
1337 HeapFree( GetProcessHeap(), 0, new_redir );
1338 return;
1341 sa.nLength = sizeof(sa);
1342 sa.lpSecurityDescriptor = NULL;
1343 sa.bInheritHandle = TRUE;
1346 * Redirect stdin, stdout and/or stderr if required.
1349 /* STDIN could come from a preceding pipe, so delete on close if it does */
1350 if (cmdList && (*cmdList)->pipeFile[0] != 0x00) {
1351 WINE_TRACE("Input coming from %s\n", wine_dbgstr_w((*cmdList)->pipeFile));
1352 h = CreateFileW((*cmdList)->pipeFile, GENERIC_READ,
1353 FILE_SHARE_READ, &sa, OPEN_EXISTING,
1354 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE, NULL);
1355 if (h == INVALID_HANDLE_VALUE) {
1356 WCMD_print_error ();
1357 HeapFree( GetProcessHeap(), 0, cmd );
1358 HeapFree( GetProcessHeap(), 0, new_redir );
1359 return;
1361 SetStdHandle (STD_INPUT_HANDLE, h);
1363 /* No need to remember the temporary name any longer once opened */
1364 (*cmdList)->pipeFile[0] = 0x00;
1366 /* Otherwise STDIN could come from a '<' redirect */
1367 } else if ((p = strchrW(new_redir,'<')) != NULL) {
1368 h = CreateFileW(WCMD_parameter(++p, 0, NULL, NULL), GENERIC_READ, FILE_SHARE_READ,
1369 &sa, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
1370 if (h == INVALID_HANDLE_VALUE) {
1371 WCMD_print_error ();
1372 HeapFree( GetProcessHeap(), 0, cmd );
1373 HeapFree( GetProcessHeap(), 0, new_redir );
1374 return;
1376 SetStdHandle (STD_INPUT_HANDLE, h);
1379 /* Scan the whole command looking for > and 2> */
1380 redir = new_redir;
1381 while (redir != NULL && ((p = strchrW(redir,'>')) != NULL)) {
1382 int handle = 0;
1384 if (p > redir && (*(p-1)=='2'))
1385 handle = 2;
1386 else
1387 handle = 1;
1389 p++;
1390 if ('>' == *p) {
1391 creationDisposition = OPEN_ALWAYS;
1392 p++;
1394 else {
1395 creationDisposition = CREATE_ALWAYS;
1398 /* Add support for 2>&1 */
1399 redir = p;
1400 if (*p == '&') {
1401 int idx = *(p+1) - '0';
1403 if (DuplicateHandle(GetCurrentProcess(),
1404 GetStdHandle(idx_stdhandles[idx]),
1405 GetCurrentProcess(),
1407 0, TRUE, DUPLICATE_SAME_ACCESS) == 0) {
1408 WINE_FIXME("Duplicating handle failed with gle %d\n", GetLastError());
1410 WINE_TRACE("Redirect %d (%p) to %d (%p)\n", handle, GetStdHandle(idx_stdhandles[idx]), idx, h);
1412 } else {
1413 WCHAR *param = WCMD_parameter(p, 0, NULL, NULL);
1414 h = CreateFileW(param, GENERIC_WRITE, 0, &sa, creationDisposition,
1415 FILE_ATTRIBUTE_NORMAL, NULL);
1416 if (h == INVALID_HANDLE_VALUE) {
1417 WCMD_print_error ();
1418 HeapFree( GetProcessHeap(), 0, cmd );
1419 HeapFree( GetProcessHeap(), 0, new_redir );
1420 return;
1422 if (SetFilePointer (h, 0, NULL, FILE_END) ==
1423 INVALID_SET_FILE_POINTER) {
1424 WCMD_print_error ();
1426 WINE_TRACE("Redirect %d to '%s' (%p)\n", handle, wine_dbgstr_w(param), h);
1429 SetStdHandle (idx_stdhandles[handle], h);
1433 * Strip leading whitespaces, and a '@' if supplied
1435 whichcmd = WCMD_skip_leading_spaces(cmd);
1436 WINE_TRACE("Command: '%s'\n", wine_dbgstr_w(cmd));
1437 if (whichcmd[0] == '@') whichcmd++;
1440 * Check if the command entered is internal. If it is, pass the rest of the
1441 * line down to the command. If not try to run a program.
1444 count = 0;
1445 while (IsCharAlphaNumericW(whichcmd[count])) {
1446 count++;
1448 for (i=0; i<=WCMD_EXIT; i++) {
1449 if (CompareStringW(LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
1450 whichcmd, count, inbuilt[i], -1) == CSTR_EQUAL) break;
1452 p = WCMD_skip_leading_spaces (&whichcmd[count]);
1453 WCMD_parse (p, quals, param1, param2);
1454 WINE_TRACE("param1: %s, param2: %s\n", wine_dbgstr_w(param1), wine_dbgstr_w(param2));
1456 if (i <= WCMD_EXIT && (p[0] == '/') && (p[1] == '?')) {
1457 /* this is a help request for a builtin program */
1458 i = WCMD_HELP;
1459 memcpy(p, whichcmd, count * sizeof(WCHAR));
1460 p[count] = '\0';
1464 switch (i) {
1466 case WCMD_CALL:
1467 WCMD_call (p);
1468 break;
1469 case WCMD_CD:
1470 case WCMD_CHDIR:
1471 WCMD_setshow_default (p);
1472 break;
1473 case WCMD_CLS:
1474 WCMD_clear_screen ();
1475 break;
1476 case WCMD_COPY:
1477 WCMD_copy ();
1478 break;
1479 case WCMD_CTTY:
1480 WCMD_change_tty ();
1481 break;
1482 case WCMD_DATE:
1483 WCMD_setshow_date ();
1484 break;
1485 case WCMD_DEL:
1486 case WCMD_ERASE:
1487 WCMD_delete (p);
1488 break;
1489 case WCMD_DIR:
1490 WCMD_directory (p);
1491 break;
1492 case WCMD_ECHO:
1493 WCMD_echo(&whichcmd[count]);
1494 break;
1495 case WCMD_FOR:
1496 WCMD_for (p, cmdList);
1497 break;
1498 case WCMD_GOTO:
1499 WCMD_goto (cmdList);
1500 break;
1501 case WCMD_HELP:
1502 WCMD_give_help (p);
1503 break;
1504 case WCMD_IF:
1505 WCMD_if (p, cmdList);
1506 break;
1507 case WCMD_LABEL:
1508 WCMD_volume (TRUE, p);
1509 break;
1510 case WCMD_MD:
1511 case WCMD_MKDIR:
1512 WCMD_create_dir (p);
1513 break;
1514 case WCMD_MOVE:
1515 WCMD_move ();
1516 break;
1517 case WCMD_PATH:
1518 WCMD_setshow_path (p);
1519 break;
1520 case WCMD_PAUSE:
1521 WCMD_pause ();
1522 break;
1523 case WCMD_PROMPT:
1524 WCMD_setshow_prompt ();
1525 break;
1526 case WCMD_REM:
1527 break;
1528 case WCMD_REN:
1529 case WCMD_RENAME:
1530 WCMD_rename ();
1531 break;
1532 case WCMD_RD:
1533 case WCMD_RMDIR:
1534 WCMD_remove_dir (p);
1535 break;
1536 case WCMD_SETLOCAL:
1537 WCMD_setlocal(p);
1538 break;
1539 case WCMD_ENDLOCAL:
1540 WCMD_endlocal();
1541 break;
1542 case WCMD_SET:
1543 WCMD_setshow_env (p);
1544 break;
1545 case WCMD_SHIFT:
1546 WCMD_shift (p);
1547 break;
1548 case WCMD_TIME:
1549 WCMD_setshow_time ();
1550 break;
1551 case WCMD_TITLE:
1552 if (strlenW(&whichcmd[count]) > 0)
1553 WCMD_title(&whichcmd[count+1]);
1554 break;
1555 case WCMD_TYPE:
1556 WCMD_type (p);
1557 break;
1558 case WCMD_VER:
1559 WCMD_output(newline);
1560 WCMD_version ();
1561 break;
1562 case WCMD_VERIFY:
1563 WCMD_verify (p);
1564 break;
1565 case WCMD_VOL:
1566 WCMD_volume (FALSE, p);
1567 break;
1568 case WCMD_PUSHD:
1569 WCMD_pushd(p);
1570 break;
1571 case WCMD_POPD:
1572 WCMD_popd();
1573 break;
1574 case WCMD_ASSOC:
1575 WCMD_assoc(p, TRUE);
1576 break;
1577 case WCMD_COLOR:
1578 WCMD_color();
1579 break;
1580 case WCMD_FTYPE:
1581 WCMD_assoc(p, FALSE);
1582 break;
1583 case WCMD_MORE:
1584 WCMD_more(p);
1585 break;
1586 case WCMD_CHOICE:
1587 WCMD_choice(p);
1588 break;
1589 case WCMD_EXIT:
1590 WCMD_exit (cmdList);
1591 break;
1592 default:
1593 prev_echo_mode = echo_mode;
1594 WCMD_run_program (whichcmd, 0);
1595 echo_mode = prev_echo_mode;
1597 HeapFree( GetProcessHeap(), 0, cmd );
1598 HeapFree( GetProcessHeap(), 0, new_redir );
1600 /* Restore old handles */
1601 for (i=0; i<3; i++) {
1602 if (old_stdhandles[i] != GetStdHandle(idx_stdhandles[i])) {
1603 CloseHandle (GetStdHandle (idx_stdhandles[i]));
1604 SetStdHandle (idx_stdhandles[i], old_stdhandles[i]);
1609 /*************************************************************************
1610 * WCMD_LoadMessage
1611 * Load a string from the resource file, handling any error
1612 * Returns string retrieved from resource file
1614 WCHAR *WCMD_LoadMessage(UINT id) {
1615 static WCHAR msg[2048];
1616 static const WCHAR failedMsg[] = {'F','a','i','l','e','d','!','\0'};
1618 if (!LoadStringW(GetModuleHandleW(NULL), id, msg, sizeof(msg)/sizeof(WCHAR))) {
1619 WINE_FIXME("LoadString failed with %d\n", GetLastError());
1620 strcpyW(msg, failedMsg);
1622 return msg;
1625 /***************************************************************************
1626 * WCMD_DumpCommands
1628 * Dumps out the parsed command line to ensure syntax is correct
1630 static void WCMD_DumpCommands(CMD_LIST *commands) {
1631 CMD_LIST *thisCmd = commands;
1633 WINE_TRACE("Parsed line:\n");
1634 while (thisCmd != NULL) {
1635 WINE_TRACE("%p %d %2.2d %p %s Redir:%s\n",
1636 thisCmd,
1637 thisCmd->prevDelim,
1638 thisCmd->bracketDepth,
1639 thisCmd->nextcommand,
1640 wine_dbgstr_w(thisCmd->command),
1641 wine_dbgstr_w(thisCmd->redirects));
1642 thisCmd = thisCmd->nextcommand;
1646 /***************************************************************************
1647 * WCMD_addCommand
1649 * Adds a command to the current command list
1651 static void WCMD_addCommand(WCHAR *command, int *commandLen,
1652 WCHAR *redirs, int *redirLen,
1653 WCHAR **copyTo, int **copyToLen,
1654 CMD_DELIMITERS prevDelim, int curDepth,
1655 CMD_LIST **lastEntry, CMD_LIST **output) {
1657 CMD_LIST *thisEntry = NULL;
1659 /* Allocate storage for command */
1660 thisEntry = HeapAlloc(GetProcessHeap(), 0, sizeof(CMD_LIST));
1662 /* Copy in the command */
1663 if (command) {
1664 thisEntry->command = HeapAlloc(GetProcessHeap(), 0,
1665 (*commandLen+1) * sizeof(WCHAR));
1666 memcpy(thisEntry->command, command, *commandLen * sizeof(WCHAR));
1667 thisEntry->command[*commandLen] = 0x00;
1669 /* Copy in the redirects */
1670 thisEntry->redirects = HeapAlloc(GetProcessHeap(), 0,
1671 (*redirLen+1) * sizeof(WCHAR));
1672 memcpy(thisEntry->redirects, redirs, *redirLen * sizeof(WCHAR));
1673 thisEntry->redirects[*redirLen] = 0x00;
1674 thisEntry->pipeFile[0] = 0x00;
1676 /* Reset the lengths */
1677 *commandLen = 0;
1678 *redirLen = 0;
1679 *copyToLen = commandLen;
1680 *copyTo = command;
1682 } else {
1683 thisEntry->command = NULL;
1684 thisEntry->redirects = NULL;
1685 thisEntry->pipeFile[0] = 0x00;
1688 /* Fill in other fields */
1689 thisEntry->nextcommand = NULL;
1690 thisEntry->prevDelim = prevDelim;
1691 thisEntry->bracketDepth = curDepth;
1692 if (*lastEntry) {
1693 (*lastEntry)->nextcommand = thisEntry;
1694 } else {
1695 *output = thisEntry;
1697 *lastEntry = thisEntry;
1701 /***************************************************************************
1702 * WCMD_IsEndQuote
1704 * Checks if the quote pointed to is the end-quote.
1706 * Quotes end if:
1708 * 1) The current parameter ends at EOL or at the beginning
1709 * of a redirection or pipe and not in a quote section.
1711 * 2) If the next character is a space and not in a quote section.
1713 * Returns TRUE if this is an end quote, and FALSE if it is not.
1716 static BOOL WCMD_IsEndQuote(const WCHAR *quote, int quoteIndex)
1718 int quoteCount = quoteIndex;
1719 int i;
1721 /* If we are not in a quoted section, then we are not an end-quote */
1722 if(quoteIndex == 0)
1724 return FALSE;
1727 /* Check how many quotes are left for this parameter */
1728 for(i=0;quote[i];i++)
1730 if(quote[i] == '"')
1732 quoteCount++;
1735 /* Quote counting ends at EOL, redirection, space or pipe if current quote is complete */
1736 else if(((quoteCount % 2) == 0)
1737 && ((quote[i] == '<') || (quote[i] == '>') || (quote[i] == '|') || (quote[i] == ' ')))
1739 break;
1743 /* If the quote is part of the last part of a series of quotes-on-quotes, then it must
1744 be an end-quote */
1745 if(quoteIndex >= (quoteCount / 2))
1747 return TRUE;
1750 /* No cigar */
1751 return FALSE;
1754 /***************************************************************************
1755 * WCMD_ReadAndParseLine
1757 * Either uses supplied input or
1758 * Reads a file from the handle, and then...
1759 * Parse the text buffer, splitting into separate commands
1760 * - unquoted && strings split 2 commands but the 2nd is flagged as
1761 * following an &&
1762 * - ( as the first character just ups the bracket depth
1763 * - unquoted ) when bracket depth > 0 terminates a bracket and
1764 * adds a CMD_LIST structure with null command
1765 * - Anything else gets put into the command string (including
1766 * redirects)
1768 WCHAR *WCMD_ReadAndParseLine(const WCHAR *optionalcmd, CMD_LIST **output, HANDLE readFrom) {
1770 WCHAR *curPos;
1771 int inQuotes = 0;
1772 WCHAR curString[MAXSTRING];
1773 int curStringLen = 0;
1774 WCHAR curRedirs[MAXSTRING];
1775 int curRedirsLen = 0;
1776 WCHAR *curCopyTo;
1777 int *curLen;
1778 int curDepth = 0;
1779 CMD_LIST *lastEntry = NULL;
1780 CMD_DELIMITERS prevDelim = CMD_NONE;
1781 static WCHAR *extraSpace = NULL; /* Deliberately never freed */
1782 static const WCHAR remCmd[] = {'r','e','m'};
1783 static const WCHAR forCmd[] = {'f','o','r'};
1784 static const WCHAR ifCmd[] = {'i','f'};
1785 static const WCHAR ifElse[] = {'e','l','s','e'};
1786 BOOL inRem = FALSE;
1787 BOOL inFor = FALSE;
1788 BOOL inIn = FALSE;
1789 BOOL inIf = FALSE;
1790 BOOL inElse= FALSE;
1791 BOOL onlyWhiteSpace = FALSE;
1792 BOOL lastWasWhiteSpace = FALSE;
1793 BOOL lastWasDo = FALSE;
1794 BOOL lastWasIn = FALSE;
1795 BOOL lastWasElse = FALSE;
1796 BOOL lastWasRedirect = TRUE;
1798 /* Allocate working space for a command read from keyboard, file etc */
1799 if (!extraSpace)
1800 extraSpace = HeapAlloc(GetProcessHeap(), 0, (MAXSTRING+1) * sizeof(WCHAR));
1801 if (!extraSpace)
1803 WINE_ERR("Could not allocate memory for extraSpace\n");
1804 return NULL;
1807 /* If initial command read in, use that, otherwise get input from handle */
1808 if (optionalcmd != NULL) {
1809 strcpyW(extraSpace, optionalcmd);
1810 } else if (readFrom == INVALID_HANDLE_VALUE) {
1811 WINE_FIXME("No command nor handle supplied\n");
1812 } else {
1813 if (WCMD_fgets(extraSpace, MAXSTRING, readFrom) == NULL) return NULL;
1815 curPos = extraSpace;
1817 /* Handle truncated input - issue warning */
1818 if (strlenW(extraSpace) == MAXSTRING -1) {
1819 WCMD_output_asis(WCMD_LoadMessage(WCMD_TRUNCATEDLINE));
1820 WCMD_output_asis(extraSpace);
1821 WCMD_output_asis(newline);
1824 /* Replace env vars if in a batch context */
1825 if (context) handleExpansion(extraSpace, FALSE, NULL, NULL);
1826 /* Show prompt before batch line IF echo is on and in batch program */
1827 if (context && echo_mode && extraSpace[0] && (extraSpace[0] != '@')) {
1828 static const WCHAR spc[]={' ','\0'};
1829 static const WCHAR echoDot[] = {'e','c','h','o','.'};
1830 static const WCHAR echoCol[] = {'e','c','h','o',':'};
1831 const DWORD len = sizeof(echoDot)/sizeof(echoDot[0]);
1832 DWORD curr_size = strlenW(extraSpace);
1833 DWORD min_len = (curr_size < len ? curr_size : len);
1834 WCMD_show_prompt();
1835 WCMD_output_asis(extraSpace);
1836 /* I don't know why Windows puts a space here but it does */
1837 /* Except for lines starting with 'echo.' or 'echo:'. Ask MS why */
1838 if (CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
1839 extraSpace, min_len, echoDot, len) != CSTR_EQUAL
1840 && CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
1841 extraSpace, min_len, echoCol, len) != CSTR_EQUAL)
1843 WCMD_output_asis(spc);
1845 WCMD_output_asis(newline);
1848 /* Start with an empty string, copying to the command string */
1849 curStringLen = 0;
1850 curRedirsLen = 0;
1851 curCopyTo = curString;
1852 curLen = &curStringLen;
1853 lastWasRedirect = FALSE; /* Required for eg spaces between > and filename */
1855 /* Parse every character on the line being processed */
1856 while (*curPos != 0x00) {
1858 WCHAR thisChar;
1860 /* Debugging AID:
1861 WINE_TRACE("Looking at '%c' (len:%d, lws:%d, ows:%d)\n", *curPos, *curLen,
1862 lastWasWhiteSpace, onlyWhiteSpace);
1865 /* Certain commands need special handling */
1866 if (curStringLen == 0 && curCopyTo == curString) {
1867 static const WCHAR forDO[] = {'d','o'};
1869 /* If command starts with 'rem ', ignore any &&, ( etc. */
1870 if (WCMD_keyword_ws_found(remCmd, sizeof(remCmd)/sizeof(remCmd[0]), curPos)) {
1871 inRem = TRUE;
1873 } else if (WCMD_keyword_ws_found(forCmd, sizeof(forCmd)/sizeof(forCmd[0]), curPos)) {
1874 inFor = TRUE;
1876 /* If command starts with 'if ' or 'else ', handle ('s mid line. We should ensure this
1877 is only true in the command portion of the IF statement, but this
1878 should suffice for now
1879 FIXME: Silly syntax like "if 1(==1( (
1880 echo they equal
1881 )" will be parsed wrong */
1882 } else if (WCMD_keyword_ws_found(ifCmd, sizeof(ifCmd)/sizeof(ifCmd[0]), curPos)) {
1883 inIf = TRUE;
1885 } else if (WCMD_keyword_ws_found(ifElse, sizeof(ifElse)/sizeof(ifElse[0]), curPos)) {
1886 const int keyw_len = sizeof(ifElse)/sizeof(ifElse[0]) + 1;
1887 inElse = TRUE;
1888 lastWasElse = TRUE;
1889 onlyWhiteSpace = TRUE;
1890 memcpy(&curCopyTo[*curLen], curPos, keyw_len*sizeof(WCHAR));
1891 (*curLen)+=keyw_len;
1892 curPos+=keyw_len;
1893 continue;
1895 /* In a for loop, the DO command will follow a close bracket followed by
1896 whitespace, followed by DO, ie closeBracket inserts a NULL entry, curLen
1897 is then 0, and all whitespace is skipped */
1898 } else if (inFor &&
1899 WCMD_keyword_ws_found(forDO, sizeof(forDO)/sizeof(forDO[0]), curPos)) {
1900 const int keyw_len = sizeof(forDO)/sizeof(forDO[0]) + 1;
1901 WINE_TRACE("Found 'DO '\n");
1902 lastWasDo = TRUE;
1903 onlyWhiteSpace = TRUE;
1904 memcpy(&curCopyTo[*curLen], curPos, keyw_len*sizeof(WCHAR));
1905 (*curLen)+=keyw_len;
1906 curPos+=keyw_len;
1907 continue;
1909 } else if (curCopyTo == curString) {
1911 /* Special handling for the 'FOR' command */
1912 if (inFor && lastWasWhiteSpace) {
1913 static const WCHAR forIN[] = {'i','n'};
1915 WINE_TRACE("Found 'FOR ', comparing next parm: '%s'\n", wine_dbgstr_w(curPos));
1917 if (WCMD_keyword_ws_found(forIN, sizeof(forIN)/sizeof(forIN[0]), curPos)) {
1918 const int keyw_len = sizeof(forIN)/sizeof(forIN[0]) + 1;
1919 WINE_TRACE("Found 'IN '\n");
1920 lastWasIn = TRUE;
1921 onlyWhiteSpace = TRUE;
1922 memcpy(&curCopyTo[*curLen], curPos, keyw_len*sizeof(WCHAR));
1923 (*curLen)+=keyw_len;
1924 curPos+=keyw_len;
1925 continue;
1930 /* Nothing 'ends' a REM statement and &&, quotes etc are ineffective,
1931 so just use the default processing ie skip character specific
1932 matching below */
1933 if (!inRem) thisChar = *curPos;
1934 else thisChar = 'X'; /* Character with no special processing */
1936 lastWasWhiteSpace = FALSE; /* Will be reset below */
1938 switch (thisChar) {
1940 case '=': /* drop through - ignore token delimiters at the start of a command */
1941 case ',': /* drop through - ignore token delimiters at the start of a command */
1942 case '\t':/* drop through - ignore token delimiters at the start of a command */
1943 case ' ':
1944 /* If a redirect in place, it ends here */
1945 if (!inQuotes && !lastWasRedirect) {
1947 /* If finishing off a redirect, add a whitespace delimiter */
1948 if (curCopyTo == curRedirs) {
1949 curCopyTo[(*curLen)++] = ' ';
1951 curCopyTo = curString;
1952 curLen = &curStringLen;
1954 if (*curLen > 0) {
1955 curCopyTo[(*curLen)++] = *curPos;
1958 /* Remember just processed whitespace */
1959 lastWasWhiteSpace = TRUE;
1961 break;
1963 case '>': /* drop through - handle redirect chars the same */
1964 case '<':
1965 /* Make a redirect start here */
1966 if (!inQuotes) {
1967 curCopyTo = curRedirs;
1968 curLen = &curRedirsLen;
1969 lastWasRedirect = TRUE;
1972 /* See if 1>, 2> etc, in which case we have some patching up
1973 to do (provided there's a preceding whitespace, and enough
1974 chars read so far) */
1975 if (curStringLen > 2
1976 && (*(curPos-1)>='1') && (*(curPos-1)<='9')
1977 && ((*(curPos-2)==' ') || (*(curPos-2)=='\t'))) {
1978 curStringLen--;
1979 curString[curStringLen] = 0x00;
1980 curCopyTo[(*curLen)++] = *(curPos-1);
1983 curCopyTo[(*curLen)++] = *curPos;
1985 /* If a redirect is immediately followed by '&' (ie. 2>&1) then
1986 do not process that ampersand as an AND operator */
1987 if (thisChar == '>' && *(curPos+1) == '&') {
1988 curCopyTo[(*curLen)++] = *(curPos+1);
1989 curPos++;
1991 break;
1993 case '|': /* Pipe character only if not || */
1994 if (!inQuotes) {
1995 lastWasRedirect = FALSE;
1997 /* Add an entry to the command list */
1998 if (curStringLen > 0) {
2000 /* Add the current command */
2001 WCMD_addCommand(curString, &curStringLen,
2002 curRedirs, &curRedirsLen,
2003 &curCopyTo, &curLen,
2004 prevDelim, curDepth,
2005 &lastEntry, output);
2009 if (*(curPos+1) == '|') {
2010 curPos++; /* Skip other | */
2011 prevDelim = CMD_ONFAILURE;
2012 } else {
2013 prevDelim = CMD_PIPE;
2015 } else {
2016 curCopyTo[(*curLen)++] = *curPos;
2018 break;
2020 case '"': if (WCMD_IsEndQuote(curPos, inQuotes)) {
2021 inQuotes--;
2022 } else {
2023 inQuotes++; /* Quotes within quotes are fun! */
2025 curCopyTo[(*curLen)++] = *curPos;
2026 lastWasRedirect = FALSE;
2027 break;
2029 case '(': /* If a '(' is the first non whitespace in a command portion
2030 ie start of line or just after &&, then we read until an
2031 unquoted ) is found */
2032 WINE_TRACE("Found '(' conditions: curLen(%d), inQ(%d), onlyWS(%d)"
2033 ", for(%d, In:%d, Do:%d)"
2034 ", if(%d, else:%d, lwe:%d)\n",
2035 *curLen, inQuotes,
2036 onlyWhiteSpace,
2037 inFor, lastWasIn, lastWasDo,
2038 inIf, inElse, lastWasElse);
2039 lastWasRedirect = FALSE;
2041 /* Ignore open brackets inside the for set */
2042 if (*curLen == 0 && !inIn) {
2043 curDepth++;
2045 /* If in quotes, ignore brackets */
2046 } else if (inQuotes) {
2047 curCopyTo[(*curLen)++] = *curPos;
2049 /* In a FOR loop, an unquoted '(' may occur straight after
2050 IN or DO
2051 In an IF statement just handle it regardless as we don't
2052 parse the operands
2053 In an ELSE statement, only allow it straight away after
2054 the ELSE and whitespace
2056 } else if (inIf ||
2057 (inElse && lastWasElse && onlyWhiteSpace) ||
2058 (inFor && (lastWasIn || lastWasDo) && onlyWhiteSpace)) {
2060 /* If entering into an 'IN', set inIn */
2061 if (inFor && lastWasIn && onlyWhiteSpace) {
2062 WINE_TRACE("Inside an IN\n");
2063 inIn = TRUE;
2066 /* Add the current command */
2067 WCMD_addCommand(curString, &curStringLen,
2068 curRedirs, &curRedirsLen,
2069 &curCopyTo, &curLen,
2070 prevDelim, curDepth,
2071 &lastEntry, output);
2073 curDepth++;
2074 } else {
2075 curCopyTo[(*curLen)++] = *curPos;
2077 break;
2079 case '&': if (!inQuotes) {
2080 lastWasRedirect = FALSE;
2082 /* Add an entry to the command list */
2083 if (curStringLen > 0) {
2085 /* Add the current command */
2086 WCMD_addCommand(curString, &curStringLen,
2087 curRedirs, &curRedirsLen,
2088 &curCopyTo, &curLen,
2089 prevDelim, curDepth,
2090 &lastEntry, output);
2094 if (*(curPos+1) == '&') {
2095 curPos++; /* Skip other & */
2096 prevDelim = CMD_ONSUCCESS;
2097 } else {
2098 prevDelim = CMD_NONE;
2100 } else {
2101 curCopyTo[(*curLen)++] = *curPos;
2103 break;
2105 case ')': if (!inQuotes && curDepth > 0) {
2106 lastWasRedirect = FALSE;
2108 /* Add the current command if there is one */
2109 if (curStringLen) {
2111 /* Add the current command */
2112 WCMD_addCommand(curString, &curStringLen,
2113 curRedirs, &curRedirsLen,
2114 &curCopyTo, &curLen,
2115 prevDelim, curDepth,
2116 &lastEntry, output);
2119 /* Add an empty entry to the command list */
2120 prevDelim = CMD_NONE;
2121 WCMD_addCommand(NULL, &curStringLen,
2122 curRedirs, &curRedirsLen,
2123 &curCopyTo, &curLen,
2124 prevDelim, curDepth,
2125 &lastEntry, output);
2126 curDepth--;
2128 /* Leave inIn if necessary */
2129 if (inIn) inIn = FALSE;
2130 } else {
2131 curCopyTo[(*curLen)++] = *curPos;
2133 break;
2134 default:
2135 lastWasRedirect = FALSE;
2136 curCopyTo[(*curLen)++] = *curPos;
2139 curPos++;
2141 /* At various times we need to know if we have only skipped whitespace,
2142 so reset this variable and then it will remain true until a non
2143 whitespace is found */
2144 if ((thisChar != ' ') && (thisChar != '\t') && (thisChar != '\n'))
2145 onlyWhiteSpace = FALSE;
2147 /* Flag end of interest in FOR DO and IN parms once something has been processed */
2148 if (!lastWasWhiteSpace) {
2149 lastWasIn = lastWasDo = FALSE;
2152 /* If we have reached the end, add this command into the list */
2153 if (*curPos == 0x00 && *curLen > 0) {
2155 /* Add an entry to the command list */
2156 WCMD_addCommand(curString, &curStringLen,
2157 curRedirs, &curRedirsLen,
2158 &curCopyTo, &curLen,
2159 prevDelim, curDepth,
2160 &lastEntry, output);
2163 /* If we have reached the end of the string, see if bracketing outstanding */
2164 if (*curPos == 0x00 && curDepth > 0 && readFrom != INVALID_HANDLE_VALUE) {
2165 inRem = FALSE;
2166 prevDelim = CMD_NONE;
2167 inQuotes = 0;
2168 memset(extraSpace, 0x00, (MAXSTRING+1) * sizeof(WCHAR));
2170 /* Read more, skipping any blank lines */
2171 while (*extraSpace == 0x00) {
2172 if (!context) WCMD_output_asis( WCMD_LoadMessage(WCMD_MOREPROMPT));
2173 if (WCMD_fgets(extraSpace, MAXSTRING, readFrom) == NULL) break;
2175 curPos = extraSpace;
2176 if (context) handleExpansion(extraSpace, FALSE, NULL, NULL);
2177 /* Continue to echo commands IF echo is on and in batch program */
2178 if (context && echo_mode && extraSpace[0] && (extraSpace[0] != '@')) {
2179 WCMD_output_asis(extraSpace);
2180 WCMD_output_asis(newline);
2185 /* Dump out the parsed output */
2186 WCMD_DumpCommands(*output);
2188 return extraSpace;
2191 /***************************************************************************
2192 * WCMD_process_commands
2194 * Process all the commands read in so far
2196 CMD_LIST *WCMD_process_commands(CMD_LIST *thisCmd, BOOL oneBracket,
2197 const WCHAR *var, const WCHAR *val) {
2199 int bdepth = -1;
2201 if (thisCmd && oneBracket) bdepth = thisCmd->bracketDepth;
2203 /* Loop through the commands, processing them one by one */
2204 while (thisCmd) {
2206 CMD_LIST *origCmd = thisCmd;
2208 /* If processing one bracket only, and we find the end bracket
2209 entry (or less), return */
2210 if (oneBracket && !thisCmd->command &&
2211 bdepth <= thisCmd->bracketDepth) {
2212 WINE_TRACE("Finished bracket @ %p, next command is %p\n",
2213 thisCmd, thisCmd->nextcommand);
2214 return thisCmd->nextcommand;
2217 /* Ignore the NULL entries a ')' inserts (Only 'if' cares
2218 about them and it will be handled in there)
2219 Also, skip over any batch labels (eg. :fred) */
2220 if (thisCmd->command && thisCmd->command[0] != ':') {
2221 WINE_TRACE("Executing command: '%s'\n", wine_dbgstr_w(thisCmd->command));
2222 WCMD_execute (thisCmd->command, thisCmd->redirects, var, val, &thisCmd);
2225 /* Step on unless the command itself already stepped on */
2226 if (thisCmd == origCmd) thisCmd = thisCmd->nextcommand;
2228 return NULL;
2231 /***************************************************************************
2232 * WCMD_free_commands
2234 * Frees the storage held for a parsed command line
2235 * - This is not done in the process_commands, as eventually the current
2236 * pointer will be modified within the commands, and hence a single free
2237 * routine is simpler
2239 void WCMD_free_commands(CMD_LIST *cmds) {
2241 /* Loop through the commands, freeing them one by one */
2242 while (cmds) {
2243 CMD_LIST *thisCmd = cmds;
2244 cmds = cmds->nextcommand;
2245 HeapFree(GetProcessHeap(), 0, thisCmd->command);
2246 HeapFree(GetProcessHeap(), 0, thisCmd->redirects);
2247 HeapFree(GetProcessHeap(), 0, thisCmd);
2252 /*****************************************************************************
2253 * Main entry point. This is a console application so we have a main() not a
2254 * winmain().
2257 int wmain (int argc, WCHAR *argvW[])
2259 int args;
2260 WCHAR *cmd = NULL;
2261 WCHAR string[1024];
2262 WCHAR envvar[4];
2263 int opt_q;
2264 int opt_t = 0;
2265 static const WCHAR promptW[] = {'P','R','O','M','P','T','\0'};
2266 static const WCHAR defaultpromptW[] = {'$','P','$','G','\0'};
2267 char ansiVersion[100];
2268 CMD_LIST *toExecute = NULL; /* Commands left to be executed */
2270 srand(time(NULL));
2272 /* Pre initialize some messages */
2273 strcpy(ansiVersion, PACKAGE_VERSION);
2274 MultiByteToWideChar(CP_ACP, 0, ansiVersion, -1, string, 1024);
2275 wsprintfW(version_string, WCMD_LoadMessage(WCMD_VERSION), string);
2276 strcpyW(anykey, WCMD_LoadMessage(WCMD_ANYKEY));
2278 args = argc;
2279 opt_c=opt_k=opt_q=opt_s=0;
2280 while (args > 0)
2282 WCHAR c;
2283 WINE_TRACE("Command line parm: '%s'\n", wine_dbgstr_w(*argvW));
2284 if ((*argvW)[0]!='/' || (*argvW)[1]=='\0') {
2285 argvW++;
2286 args--;
2287 continue;
2290 c=(*argvW)[1];
2291 if (tolowerW(c)=='c') {
2292 opt_c=1;
2293 } else if (tolowerW(c)=='q') {
2294 opt_q=1;
2295 } else if (tolowerW(c)=='k') {
2296 opt_k=1;
2297 } else if (tolowerW(c)=='s') {
2298 opt_s=1;
2299 } else if (tolowerW(c)=='a') {
2300 unicodePipes=FALSE;
2301 } else if (tolowerW(c)=='u') {
2302 unicodePipes=TRUE;
2303 } else if (tolowerW(c)=='t' && (*argvW)[2]==':') {
2304 opt_t=strtoulW(&(*argvW)[3], NULL, 16);
2305 } else if (tolowerW(c)=='x' || tolowerW(c)=='y') {
2306 /* Ignored for compatibility with Windows */
2309 if ((*argvW)[2]==0) {
2310 argvW++;
2311 args--;
2313 else /* handle `cmd /cnotepad.exe` and `cmd /x/c ...` */
2315 *argvW+=2;
2318 if (opt_c || opt_k) /* break out of parsing immediately after c or k */
2319 break;
2322 if (opt_q) {
2323 static const WCHAR eoff[] = {'O','F','F','\0'};
2324 WCMD_echo(eoff);
2327 if (opt_c || opt_k) {
2328 int len,qcount;
2329 WCHAR** arg;
2330 int argsLeft;
2331 WCHAR* p;
2333 /* opt_s left unflagged if the command starts with and contains exactly
2334 * one quoted string (exactly two quote characters). The quoted string
2335 * must be an executable name that has whitespace and must not have the
2336 * following characters: &<>()@^| */
2338 /* Build the command to execute */
2339 len = 0;
2340 qcount = 0;
2341 argsLeft = args;
2342 for (arg = argvW; argsLeft>0; arg++,argsLeft--)
2344 int has_space,bcount;
2345 WCHAR* a;
2347 has_space=0;
2348 bcount=0;
2349 a=*arg;
2350 if( !*a ) has_space=1;
2351 while (*a!='\0') {
2352 if (*a=='\\') {
2353 bcount++;
2354 } else {
2355 if (*a==' ' || *a=='\t') {
2356 has_space=1;
2357 } else if (*a=='"') {
2358 /* doubling of '\' preceding a '"',
2359 * plus escaping of said '"'
2361 len+=2*bcount+1;
2362 qcount++;
2364 bcount=0;
2366 a++;
2368 len+=(a-*arg) + 1; /* for the separating space */
2369 if (has_space)
2371 len+=2; /* for the quotes */
2372 qcount+=2;
2376 if (qcount!=2)
2377 opt_s=1;
2379 /* check argvW[0] for a space and invalid characters */
2380 if (!opt_s) {
2381 opt_s=1;
2382 p=*argvW;
2383 while (*p!='\0') {
2384 if (*p=='&' || *p=='<' || *p=='>' || *p=='(' || *p==')'
2385 || *p=='@' || *p=='^' || *p=='|') {
2386 opt_s=1;
2387 break;
2389 if (*p==' ')
2390 opt_s=0;
2391 p++;
2395 cmd = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
2396 if (!cmd)
2397 exit(1);
2399 p = cmd;
2400 argsLeft = args;
2401 for (arg = argvW; argsLeft>0; arg++,argsLeft--)
2403 int has_space,has_quote;
2404 WCHAR* a;
2406 /* Check for quotes and spaces in this argument */
2407 has_space=has_quote=0;
2408 a=*arg;
2409 if( !*a ) has_space=1;
2410 while (*a!='\0') {
2411 if (*a==' ' || *a=='\t') {
2412 has_space=1;
2413 if (has_quote)
2414 break;
2415 } else if (*a=='"') {
2416 has_quote=1;
2417 if (has_space)
2418 break;
2420 a++;
2423 /* Now transfer it to the command line */
2424 if (has_space)
2425 *p++='"';
2426 if (has_quote) {
2427 int bcount;
2428 WCHAR* a;
2430 bcount=0;
2431 a=*arg;
2432 while (*a!='\0') {
2433 if (*a=='\\') {
2434 *p++=*a;
2435 bcount++;
2436 } else {
2437 if (*a=='"') {
2438 int i;
2440 /* Double all the '\\' preceding this '"', plus one */
2441 for (i=0;i<=bcount;i++)
2442 *p++='\\';
2443 *p++='"';
2444 } else {
2445 *p++=*a;
2447 bcount=0;
2449 a++;
2451 } else {
2452 strcpyW(p,*arg);
2453 p+=strlenW(*arg);
2455 if (has_space)
2456 *p++='"';
2457 *p++=' ';
2459 if (p > cmd)
2460 p--; /* remove last space */
2461 *p = '\0';
2463 WINE_TRACE("/c command line: '%s'\n", wine_dbgstr_w(cmd));
2465 /* strip first and last quote characters if opt_s; check for invalid
2466 * executable is done later */
2467 if (opt_s && *cmd=='\"')
2468 WCMD_opt_s_strip_quotes(cmd);
2471 if (opt_c) {
2472 /* If we do a "cmd /c command", we don't want to allocate a new
2473 * console since the command returns immediately. Rather, we use
2474 * the currently allocated input and output handles. This allows
2475 * us to pipe to and read from the command interpreter.
2478 /* Parse the command string, without reading any more input */
2479 WCMD_ReadAndParseLine(cmd, &toExecute, INVALID_HANDLE_VALUE);
2480 WCMD_process_commands(toExecute, FALSE, NULL, NULL);
2481 WCMD_free_commands(toExecute);
2482 toExecute = NULL;
2484 HeapFree(GetProcessHeap(), 0, cmd);
2485 return errorlevel;
2488 SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), ENABLE_LINE_INPUT |
2489 ENABLE_ECHO_INPUT | ENABLE_PROCESSED_INPUT);
2490 SetConsoleTitleW(WCMD_LoadMessage(WCMD_CONSTITLE));
2492 /* Note: cmd.exe /c dir does not get a new color, /k dir does */
2493 if (opt_t) {
2494 if (!(((opt_t & 0xF0) >> 4) == (opt_t & 0x0F))) {
2495 defaultColor = opt_t & 0xFF;
2496 param1[0] = 0x00;
2497 WCMD_color();
2499 } else {
2500 /* Check HKCU\Software\Microsoft\Command Processor
2501 Then HKLM\Software\Microsoft\Command Processor
2502 for defaultcolour value
2503 Note Can be supplied as DWORD or REG_SZ
2504 Note2 When supplied as REG_SZ it's in decimal!!! */
2505 HKEY key;
2506 DWORD type;
2507 DWORD value=0, size=4;
2508 static const WCHAR regKeyW[] = {'S','o','f','t','w','a','r','e','\\',
2509 'M','i','c','r','o','s','o','f','t','\\',
2510 'C','o','m','m','a','n','d',' ','P','r','o','c','e','s','s','o','r','\0'};
2511 static const WCHAR dfltColorW[] = {'D','e','f','a','u','l','t','C','o','l','o','r','\0'};
2513 if (RegOpenKeyExW(HKEY_CURRENT_USER, regKeyW,
2514 0, KEY_READ, &key) == ERROR_SUCCESS) {
2515 WCHAR strvalue[4];
2517 /* See if DWORD or REG_SZ */
2518 if (RegQueryValueExW(key, dfltColorW, NULL, &type,
2519 NULL, NULL) == ERROR_SUCCESS) {
2520 if (type == REG_DWORD) {
2521 size = sizeof(DWORD);
2522 RegQueryValueExW(key, dfltColorW, NULL, NULL,
2523 (LPBYTE)&value, &size);
2524 } else if (type == REG_SZ) {
2525 size = sizeof(strvalue)/sizeof(WCHAR);
2526 RegQueryValueExW(key, dfltColorW, NULL, NULL,
2527 (LPBYTE)strvalue, &size);
2528 value = strtoulW(strvalue, NULL, 10);
2531 RegCloseKey(key);
2534 if (value == 0 && RegOpenKeyExW(HKEY_LOCAL_MACHINE, 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 one found, set the screen to that colour */
2556 if (!(((value & 0xF0) >> 4) == (value & 0x0F))) {
2557 defaultColor = value & 0xFF;
2558 param1[0] = 0x00;
2559 WCMD_color();
2564 /* Save cwd into appropriate env var */
2565 GetCurrentDirectoryW(1024, string);
2566 if (IsCharAlphaW(string[0]) && string[1] == ':') {
2567 static const WCHAR fmt[] = {'=','%','c',':','\0'};
2568 wsprintfW(envvar, fmt, string[0]);
2569 SetEnvironmentVariableW(envvar, string);
2570 WINE_TRACE("Set %s to %s\n", wine_dbgstr_w(envvar), wine_dbgstr_w(string));
2573 if (opt_k) {
2574 /* Parse the command string, without reading any more input */
2575 WCMD_ReadAndParseLine(cmd, &toExecute, INVALID_HANDLE_VALUE);
2576 WCMD_process_commands(toExecute, FALSE, NULL, NULL);
2577 WCMD_free_commands(toExecute);
2578 toExecute = NULL;
2579 HeapFree(GetProcessHeap(), 0, cmd);
2583 * Loop forever getting commands and executing them.
2586 SetEnvironmentVariableW(promptW, defaultpromptW);
2587 WCMD_version ();
2588 while (TRUE) {
2590 /* Read until EOF (which for std input is never, but if redirect
2591 in place, may occur */
2592 if (echo_mode) WCMD_show_prompt();
2593 if (WCMD_ReadAndParseLine(NULL, &toExecute,
2594 GetStdHandle(STD_INPUT_HANDLE)) == NULL)
2595 break;
2596 WCMD_process_commands(toExecute, FALSE, NULL, NULL);
2597 WCMD_free_commands(toExecute);
2598 toExecute = NULL;
2600 return 0;