winex11: Get rid of the non-Xrender client-side font rendering.
[wine/multimedia.git] / programs / cmd / wcmdmain.c
blobe306d5213d34d9c6e16ab28fab33db329551731a
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 const WCHAR space[] = {' ','\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, DWORD 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 DWORD 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 DWORD 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 /***************************************************************************
237 * WCMD_Readfile
239 * Read characters in from a console/file, returning result in Unicode
241 BOOL WCMD_ReadFile(const HANDLE hIn, WCHAR *intoBuf, const DWORD maxChars, LPDWORD charsRead)
243 DWORD numRead;
244 char *buffer;
246 if (WCMD_is_console_handle(hIn))
247 /* Try to read from console as Unicode */
248 return ReadConsoleW(hIn, intoBuf, maxChars, charsRead, NULL);
250 /* We assume it's a file handle and read then convert from assumed OEM codepage */
251 if (!(buffer = get_file_buffer()))
252 return FALSE;
254 if (!ReadFile(hIn, buffer, maxChars, &numRead, NULL))
255 return FALSE;
257 *charsRead = MultiByteToWideChar(GetConsoleCP(), 0, buffer, numRead, intoBuf, maxChars);
259 return TRUE;
262 /*******************************************************************
263 * WCMD_output_asis_handle
265 * Send output to specified handle without formatting e.g. when message contains '%'
267 static void WCMD_output_asis_handle (DWORD std_handle, const WCHAR *message) {
268 DWORD count;
269 const WCHAR* ptr;
270 WCHAR string[1024];
271 HANDLE handle = GetStdHandle(std_handle);
273 if (paged_mode) {
274 do {
275 ptr = message;
276 while (*ptr && *ptr!='\n' && (numChars < max_width)) {
277 numChars++;
278 ptr++;
280 if (*ptr == '\n') ptr++;
281 WCMD_output_asis_len(message, ptr - message, handle);
282 numChars = 0;
283 if (++line_count >= max_height - 1) {
284 line_count = 0;
285 WCMD_output_asis_len(pagedMessage, strlenW(pagedMessage), handle);
286 WCMD_ReadFile(GetStdHandle(STD_INPUT_HANDLE), string, sizeof(string)/sizeof(WCHAR), &count);
288 } while (((message = ptr) != NULL) && (*ptr));
289 } else {
290 WCMD_output_asis_len(message, lstrlenW(message), handle);
294 /*******************************************************************
295 * WCMD_output_asis
297 * Send output to current standard output device, without formatting
298 * e.g. when message contains '%'
300 void WCMD_output_asis (const WCHAR *message) {
301 WCMD_output_asis_handle(STD_OUTPUT_HANDLE, message);
304 /*******************************************************************
305 * WCMD_output_asis_stderr
307 * Send output to current standard error device, without formatting
308 * e.g. when message contains '%'
310 void WCMD_output_asis_stderr (const WCHAR *message) {
311 WCMD_output_asis_handle(STD_ERROR_HANDLE, message);
314 /****************************************************************************
315 * WCMD_print_error
317 * Print the message for GetLastError
320 void WCMD_print_error (void) {
321 LPVOID lpMsgBuf;
322 DWORD error_code;
323 int status;
325 error_code = GetLastError ();
326 status = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
327 NULL, error_code, 0, (LPWSTR) &lpMsgBuf, 0, NULL);
328 if (!status) {
329 WINE_FIXME ("Cannot display message for error %d, status %d\n",
330 error_code, GetLastError());
331 return;
334 WCMD_output_asis_len(lpMsgBuf, lstrlenW(lpMsgBuf),
335 GetStdHandle(STD_ERROR_HANDLE));
336 LocalFree (lpMsgBuf);
337 WCMD_output_asis_len (newline, lstrlenW(newline),
338 GetStdHandle(STD_ERROR_HANDLE));
339 return;
342 /******************************************************************************
343 * WCMD_show_prompt
345 * Display the prompt on STDout
349 static void WCMD_show_prompt (void) {
351 int status;
352 WCHAR out_string[MAX_PATH], curdir[MAX_PATH], prompt_string[MAX_PATH];
353 WCHAR *p, *q;
354 DWORD len;
355 static const WCHAR envPrompt[] = {'P','R','O','M','P','T','\0'};
357 len = GetEnvironmentVariableW(envPrompt, prompt_string,
358 sizeof(prompt_string)/sizeof(WCHAR));
359 if ((len == 0) || (len >= (sizeof(prompt_string)/sizeof(WCHAR)))) {
360 static const WCHAR dfltPrompt[] = {'$','P','$','G','\0'};
361 strcpyW (prompt_string, dfltPrompt);
363 p = prompt_string;
364 q = out_string;
365 *q++ = '\r';
366 *q++ = '\n';
367 *q = '\0';
368 while (*p != '\0') {
369 if (*p != '$') {
370 *q++ = *p++;
371 *q = '\0';
373 else {
374 p++;
375 switch (toupper(*p)) {
376 case '$':
377 *q++ = '$';
378 break;
379 case 'A':
380 *q++ = '&';
381 break;
382 case 'B':
383 *q++ = '|';
384 break;
385 case 'C':
386 *q++ = '(';
387 break;
388 case 'D':
389 GetDateFormatW(LOCALE_USER_DEFAULT, DATE_SHORTDATE, NULL, NULL, q, MAX_PATH);
390 while (*q) q++;
391 break;
392 case 'E':
393 *q++ = '\E';
394 break;
395 case 'F':
396 *q++ = ')';
397 break;
398 case 'G':
399 *q++ = '>';
400 break;
401 case 'H':
402 *q++ = '\b';
403 break;
404 case 'L':
405 *q++ = '<';
406 break;
407 case 'N':
408 status = GetCurrentDirectoryW(sizeof(curdir)/sizeof(WCHAR), curdir);
409 if (status) {
410 *q++ = curdir[0];
412 break;
413 case 'P':
414 status = GetCurrentDirectoryW(sizeof(curdir)/sizeof(WCHAR), curdir);
415 if (status) {
416 strcatW (q, curdir);
417 while (*q) q++;
419 break;
420 case 'Q':
421 *q++ = '=';
422 break;
423 case 'S':
424 *q++ = ' ';
425 break;
426 case 'T':
427 GetTimeFormatW(LOCALE_USER_DEFAULT, 0, NULL, NULL, q, MAX_PATH);
428 while (*q) q++;
429 break;
430 case 'V':
431 strcatW (q, version_string);
432 while (*q) q++;
433 break;
434 case '_':
435 *q++ = '\n';
436 break;
437 case '+':
438 if (pushd_directories) {
439 memset(q, '+', pushd_directories->u.stackdepth);
440 q = q + pushd_directories->u.stackdepth;
442 break;
444 p++;
445 *q = '\0';
448 WCMD_output_asis (out_string);
452 /*************************************************************************
453 * WCMD_strdupW
454 * A wide version of strdup as its missing from unicode.h
456 WCHAR *WCMD_strdupW(const WCHAR *input) {
457 int len=strlenW(input)+1;
458 WCHAR *result = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
459 memcpy(result, input, len * sizeof(WCHAR));
460 return result;
463 /*************************************************************************
464 * WCMD_strsubstW
465 * Replaces a portion of a Unicode string with the specified string.
466 * It's up to the caller to ensure there is enough space in the
467 * destination buffer.
469 void WCMD_strsubstW(WCHAR *start, const WCHAR *next, const WCHAR *insert, int len) {
471 if (len < 0)
472 len=insert ? lstrlenW(insert) : 0;
473 if (start+len != next)
474 memmove(start+len, next, (strlenW(next) + 1) * sizeof(*next));
475 if (insert)
476 memcpy(start, insert, len * sizeof(*insert));
479 /***************************************************************************
480 * WCMD_skip_leading_spaces
482 * Return a pointer to the first non-whitespace character of string.
483 * Does not modify the input string.
485 WCHAR *WCMD_skip_leading_spaces (WCHAR *string) {
487 WCHAR *ptr;
489 ptr = string;
490 while (*ptr == ' ' || *ptr == '\t') ptr++;
491 return ptr;
494 /***************************************************************************
495 * WCMD_keyword_ws_found
497 * Checks if the string located at ptr matches a keyword (of length len)
498 * followed by a whitespace character (space or tab)
500 BOOL WCMD_keyword_ws_found(const WCHAR *keyword, int len, const WCHAR *ptr) {
501 return (CompareStringW(LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
502 ptr, len, keyword, len) == CSTR_EQUAL)
503 && ((*(ptr + len) == ' ') || (*(ptr + len) == '\t'));
506 /*************************************************************************
507 * WCMD_strip_quotes
509 * Remove first and last quote WCHARacters, preserving all other text
511 void WCMD_strip_quotes(WCHAR *cmd) {
512 WCHAR *src = cmd + 1, *dest = cmd, *lastq = NULL;
513 while((*dest=*src) != '\0') {
514 if (*src=='\"')
515 lastq=dest;
516 dest++, src++;
518 if (lastq) {
519 dest=lastq++;
520 while ((*dest++=*lastq++) != 0)
526 /*************************************************************************
527 * WCMD_is_magic_envvar
528 * Return TRUE if s is '%'magicvar'%'
529 * and is not masked by a real environment variable.
532 static inline BOOL WCMD_is_magic_envvar(const WCHAR *s, const WCHAR *magicvar)
534 int len;
536 if (s[0] != '%')
537 return FALSE; /* Didn't begin with % */
538 len = strlenW(s);
539 if (len < 2 || s[len-1] != '%')
540 return FALSE; /* Didn't end with another % */
542 if (CompareStringW(LOCALE_USER_DEFAULT,
543 NORM_IGNORECASE | SORT_STRINGSORT,
544 s+1, len-2, magicvar, -1) != CSTR_EQUAL) {
545 /* Name doesn't match. */
546 return FALSE;
549 if (GetEnvironmentVariableW(magicvar, NULL, 0) > 0) {
550 /* Masked by real environment variable. */
551 return FALSE;
554 return TRUE;
557 /*************************************************************************
558 * WCMD_expand_envvar
560 * Expands environment variables, allowing for WCHARacter substitution
562 static WCHAR *WCMD_expand_envvar(WCHAR *start,
563 const WCHAR *forVar, const WCHAR *forVal) {
564 WCHAR *endOfVar = NULL, *s;
565 WCHAR *colonpos = NULL;
566 WCHAR thisVar[MAXSTRING];
567 WCHAR thisVarContents[MAXSTRING];
568 WCHAR savedchar = 0x00;
569 int len;
571 static const WCHAR ErrorLvl[] = {'E','R','R','O','R','L','E','V','E','L','\0'};
572 static const WCHAR Date[] = {'D','A','T','E','\0'};
573 static const WCHAR Time[] = {'T','I','M','E','\0'};
574 static const WCHAR Cd[] = {'C','D','\0'};
575 static const WCHAR Random[] = {'R','A','N','D','O','M','\0'};
576 static const WCHAR Delims[] = {'%',' ',':','\0'};
578 WINE_TRACE("Expanding: %s (%s,%s)\n", wine_dbgstr_w(start),
579 wine_dbgstr_w(forVal), wine_dbgstr_w(forVar));
581 /* Find the end of the environment variable, and extract name */
582 endOfVar = strpbrkW(start+1, Delims);
584 if (endOfVar == NULL || *endOfVar==' ') {
586 /* In batch program, missing terminator for % and no following
587 ':' just removes the '%' */
588 if (context) {
589 WCMD_strsubstW(start, start + 1, NULL, 0);
590 return start;
591 } else {
593 /* In command processing, just ignore it - allows command line
594 syntax like: for %i in (a.a) do echo %i */
595 return start+1;
599 /* If ':' found, process remaining up until '%' (or stop at ':' if
600 a missing '%' */
601 if (*endOfVar==':') {
602 WCHAR *endOfVar2 = strchrW(endOfVar+1, '%');
603 if (endOfVar2 != NULL) endOfVar = endOfVar2;
606 memcpy(thisVar, start, ((endOfVar - start) + 1) * sizeof(WCHAR));
607 thisVar[(endOfVar - start)+1] = 0x00;
608 colonpos = strchrW(thisVar+1, ':');
610 /* If there's complex substitution, just need %var% for now
611 to get the expanded data to play with */
612 if (colonpos) {
613 *colonpos = '%';
614 savedchar = *(colonpos+1);
615 *(colonpos+1) = 0x00;
618 WINE_TRACE("Retrieving contents of %s\n", wine_dbgstr_w(thisVar));
620 /* Expand to contents, if unchanged, return */
621 /* Handle DATE, TIME, ERRORLEVEL and CD replacements allowing */
622 /* override if existing env var called that name */
623 if (WCMD_is_magic_envvar(thisVar, ErrorLvl)) {
624 static const WCHAR fmt[] = {'%','d','\0'};
625 wsprintfW(thisVarContents, fmt, errorlevel);
626 len = strlenW(thisVarContents);
627 } else if (WCMD_is_magic_envvar(thisVar, Date)) {
628 GetDateFormatW(LOCALE_USER_DEFAULT, DATE_SHORTDATE, NULL,
629 NULL, thisVarContents, MAXSTRING);
630 len = strlenW(thisVarContents);
631 } else if (WCMD_is_magic_envvar(thisVar, Time)) {
632 GetTimeFormatW(LOCALE_USER_DEFAULT, TIME_NOSECONDS, NULL,
633 NULL, thisVarContents, MAXSTRING);
634 len = strlenW(thisVarContents);
635 } else if (WCMD_is_magic_envvar(thisVar, Cd)) {
636 GetCurrentDirectoryW(MAXSTRING, thisVarContents);
637 len = strlenW(thisVarContents);
638 } else if (WCMD_is_magic_envvar(thisVar, Random)) {
639 static const WCHAR fmt[] = {'%','d','\0'};
640 wsprintfW(thisVarContents, fmt, rand() % 32768);
641 len = strlenW(thisVarContents);
643 /* Look for a matching 'for' variable */
644 } else if (forVar &&
645 (CompareStringW(LOCALE_USER_DEFAULT,
646 SORT_STRINGSORT,
647 thisVar,
648 (colonpos - thisVar) - 1,
649 forVar, -1) == CSTR_EQUAL)) {
650 strcpyW(thisVarContents, forVal);
651 len = strlenW(thisVarContents);
653 } else {
655 len = ExpandEnvironmentStringsW(thisVar, thisVarContents,
656 sizeof(thisVarContents)/sizeof(WCHAR));
659 if (len == 0)
660 return endOfVar+1;
662 /* In a batch program, unknown env vars are replaced with nothing,
663 note syntax %garbage:1,3% results in anything after the ':'
664 except the %
665 From the command line, you just get back what you entered */
666 if (lstrcmpiW(thisVar, thisVarContents) == 0) {
668 /* Restore the complex part after the compare */
669 if (colonpos) {
670 *colonpos = ':';
671 *(colonpos+1) = savedchar;
674 /* Command line - just ignore this */
675 if (context == NULL) return endOfVar+1;
678 /* Batch - replace unknown env var with nothing */
679 if (colonpos == NULL) {
680 WCMD_strsubstW(start, endOfVar + 1, NULL, 0);
681 } else {
682 len = strlenW(thisVar);
683 thisVar[len-1] = 0x00;
684 /* If %:...% supplied, : is retained */
685 if (colonpos == thisVar+1) {
686 WCMD_strsubstW(start, endOfVar + 1, colonpos, -1);
687 } else {
688 WCMD_strsubstW(start, endOfVar + 1, colonpos + 1, -1);
691 return start;
695 /* See if we need to do complex substitution (any ':'s), if not
696 then our work here is done */
697 if (colonpos == NULL) {
698 WCMD_strsubstW(start, endOfVar + 1, thisVarContents, -1);
699 return start;
702 /* Restore complex bit */
703 *colonpos = ':';
704 *(colonpos+1) = savedchar;
707 Handle complex substitutions:
708 xxx=yyy (replace xxx with yyy)
709 *xxx=yyy (replace up to and including xxx with yyy)
710 ~x (from x WCHARs in)
711 ~-x (from x WCHARs from the end)
712 ~x,y (from x WCHARs in for y WCHARacters)
713 ~x,-y (from x WCHARs in until y WCHARacters from the end)
716 /* ~ is substring manipulation */
717 if (savedchar == '~') {
719 int substrposition, substrlength = 0;
720 WCHAR *commapos = strchrW(colonpos+2, ',');
721 WCHAR *startCopy;
723 substrposition = atolW(colonpos+2);
724 if (commapos) substrlength = atolW(commapos+1);
726 /* Check bounds */
727 if (substrposition >= 0) {
728 startCopy = &thisVarContents[min(substrposition, len)];
729 } else {
730 startCopy = &thisVarContents[max(0, len+substrposition-1)];
733 if (commapos == NULL) {
734 /* Copy the lot */
735 WCMD_strsubstW(start, endOfVar + 1, startCopy, -1);
736 } else if (substrlength < 0) {
738 int copybytes = (len+substrlength-1)-(startCopy-thisVarContents);
739 if (copybytes > len) copybytes = len;
740 else if (copybytes < 0) copybytes = 0;
741 WCMD_strsubstW(start, endOfVar + 1, startCopy, copybytes);
742 } else {
743 WCMD_strsubstW(start, endOfVar + 1, startCopy, substrlength);
746 return start;
748 /* search and replace manipulation */
749 } else {
750 WCHAR *equalspos = strstrW(colonpos, equalW);
751 WCHAR *replacewith = equalspos+1;
752 WCHAR *found = NULL;
753 WCHAR *searchIn;
754 WCHAR *searchFor;
756 if (equalspos == NULL) return start+1;
757 s = WCMD_strdupW(endOfVar + 1);
759 /* Null terminate both strings */
760 thisVar[strlenW(thisVar)-1] = 0x00;
761 *equalspos = 0x00;
763 /* Since we need to be case insensitive, copy the 2 buffers */
764 searchIn = WCMD_strdupW(thisVarContents);
765 CharUpperBuffW(searchIn, strlenW(thisVarContents));
766 searchFor = WCMD_strdupW(colonpos+1);
767 CharUpperBuffW(searchFor, strlenW(colonpos+1));
769 /* Handle wildcard case */
770 if (*(colonpos+1) == '*') {
771 /* Search for string to replace */
772 found = strstrW(searchIn, searchFor+1);
774 if (found) {
775 /* Do replacement */
776 strcpyW(start, replacewith);
777 strcatW(start, thisVarContents + (found-searchIn) + strlenW(searchFor+1));
778 strcatW(start, s);
779 } else {
780 /* Copy as is */
781 strcpyW(start, thisVarContents);
782 strcatW(start, s);
785 } else {
786 /* Loop replacing all instances */
787 WCHAR *lastFound = searchIn;
788 WCHAR *outputposn = start;
790 *start = 0x00;
791 while ((found = strstrW(lastFound, searchFor))) {
792 lstrcpynW(outputposn,
793 thisVarContents + (lastFound-searchIn),
794 (found - lastFound)+1);
795 outputposn = outputposn + (found - lastFound);
796 strcatW(outputposn, replacewith);
797 outputposn = outputposn + strlenW(replacewith);
798 lastFound = found + strlenW(searchFor);
800 strcatW(outputposn,
801 thisVarContents + (lastFound-searchIn));
802 strcatW(outputposn, s);
804 HeapFree(GetProcessHeap(), 0, s);
805 HeapFree(GetProcessHeap(), 0, searchIn);
806 HeapFree(GetProcessHeap(), 0, searchFor);
807 return start;
809 return start+1;
812 /*****************************************************************************
813 * Expand the command. Native expands lines from batch programs as they are
814 * read in and not again, except for 'for' variable substitution.
815 * eg. As evidence, "echo %1 && shift && echo %1" or "echo %%path%%"
817 static void handleExpansion(WCHAR *cmd, BOOL justFors,
818 const WCHAR *forVariable, const WCHAR *forValue) {
820 /* For commands in a context (batch program): */
821 /* Expand environment variables in a batch file %{0-9} first */
822 /* including support for any ~ modifiers */
823 /* Additionally: */
824 /* Expand the DATE, TIME, CD, RANDOM and ERRORLEVEL special */
825 /* names allowing environment variable overrides */
826 /* NOTE: To support the %PATH:xxx% syntax, also perform */
827 /* manual expansion of environment variables here */
829 WCHAR *p = cmd;
830 WCHAR *t;
831 int i;
833 while ((p = strchrW(p, '%'))) {
835 WINE_TRACE("Translate command:%s %d (at: %s)\n",
836 wine_dbgstr_w(cmd), justFors, wine_dbgstr_w(p));
837 i = *(p+1) - '0';
839 /* Don't touch %% unless its in Batch */
840 if (!justFors && *(p+1) == '%') {
841 if (context) {
842 WCMD_strsubstW(p, p+1, NULL, 0);
844 p+=1;
846 /* Replace %~ modifications if in batch program */
847 } else if (*(p+1) == '~') {
848 WCMD_HandleTildaModifiers(&p, forVariable, forValue, justFors);
849 p++;
851 /* Replace use of %0...%9 if in batch program*/
852 } else if (!justFors && context && (i >= 0) && (i <= 9)) {
853 t = WCMD_parameter(context -> command, i + context -> shift_count[i], NULL, NULL);
854 WCMD_strsubstW(p, p+2, t, -1);
856 /* Replace use of %* if in batch program*/
857 } else if (!justFors && context && *(p+1)=='*') {
858 WCHAR *startOfParms = NULL;
859 t = WCMD_parameter(context -> command, 1, &startOfParms, NULL);
860 if (startOfParms != NULL)
861 WCMD_strsubstW(p, p+2, startOfParms, -1);
862 else
863 WCMD_strsubstW(p, p+2, NULL, 0);
865 } else if (forVariable &&
866 (CompareStringW(LOCALE_USER_DEFAULT,
867 SORT_STRINGSORT,
869 strlenW(forVariable),
870 forVariable, -1) == CSTR_EQUAL)) {
871 WCMD_strsubstW(p, p + strlenW(forVariable), forValue, -1);
873 } else if (!justFors) {
874 p = WCMD_expand_envvar(p, forVariable, forValue);
876 /* In a FOR loop, see if this is the variable to replace */
877 } else { /* Ignore %'s on second pass of batch program */
878 p++;
882 return;
886 /*******************************************************************
887 * WCMD_parse - parse a command into parameters and qualifiers.
889 * On exit, all qualifiers are concatenated into q, the first string
890 * not beginning with "/" is in p1 and the
891 * second in p2. Any subsequent non-qualifier strings are lost.
892 * Parameters in quotes are handled.
894 static void WCMD_parse (const WCHAR *s, WCHAR *q, WCHAR *p1, WCHAR *p2)
896 int p = 0;
898 *q = *p1 = *p2 = '\0';
899 while (TRUE) {
900 switch (*s) {
901 case '/':
902 *q++ = *s++;
903 while ((*s != '\0') && (*s != ' ') && *s != '/') {
904 *q++ = toupperW (*s++);
906 *q = '\0';
907 break;
908 case ' ':
909 case '\t':
910 s++;
911 break;
912 case '"':
913 s++;
914 while ((*s != '\0') && (*s != '"')) {
915 if (p == 0) *p1++ = *s++;
916 else if (p == 1) *p2++ = *s++;
917 else s++;
919 if (p == 0) *p1 = '\0';
920 if (p == 1) *p2 = '\0';
921 p++;
922 if (*s == '"') s++;
923 break;
924 case '\0':
925 return;
926 default:
927 while ((*s != '\0') && (*s != ' ') && (*s != '\t')
928 && (*s != '=') && (*s != ',') ) {
929 if (p == 0) *p1++ = *s++;
930 else if (p == 1) *p2++ = *s++;
931 else s++;
933 /* Skip concurrent parms */
934 while ((*s == ' ') || (*s == '\t') || (*s == '=') || (*s == ',') ) s++;
936 if (p == 0) *p1 = '\0';
937 if (p == 1) *p2 = '\0';
938 p++;
943 static void init_msvcrt_io_block(STARTUPINFOW* st)
945 STARTUPINFOW st_p;
946 /* fetch the parent MSVCRT info block if any, so that the child can use the
947 * same handles as its grand-father
949 st_p.cb = sizeof(STARTUPINFOW);
950 GetStartupInfoW(&st_p);
951 st->cbReserved2 = st_p.cbReserved2;
952 st->lpReserved2 = st_p.lpReserved2;
953 if (st_p.cbReserved2 && st_p.lpReserved2)
955 /* Override the entries for fd 0,1,2 if we happened
956 * to change those std handles (this depends on the way cmd sets
957 * its new input & output handles)
959 size_t sz = max(sizeof(unsigned) + (sizeof(char) + sizeof(HANDLE)) * 3, st_p.cbReserved2);
960 BYTE* ptr = HeapAlloc(GetProcessHeap(), 0, sz);
961 if (ptr)
963 unsigned num = *(unsigned*)st_p.lpReserved2;
964 char* flags = (char*)(ptr + sizeof(unsigned));
965 HANDLE* handles = (HANDLE*)(flags + num * sizeof(char));
967 memcpy(ptr, st_p.lpReserved2, st_p.cbReserved2);
968 st->cbReserved2 = sz;
969 st->lpReserved2 = ptr;
971 #define WX_OPEN 0x01 /* see dlls/msvcrt/file.c */
972 if (num <= 0 || (flags[0] & WX_OPEN))
974 handles[0] = GetStdHandle(STD_INPUT_HANDLE);
975 flags[0] |= WX_OPEN;
977 if (num <= 1 || (flags[1] & WX_OPEN))
979 handles[1] = GetStdHandle(STD_OUTPUT_HANDLE);
980 flags[1] |= WX_OPEN;
982 if (num <= 2 || (flags[2] & WX_OPEN))
984 handles[2] = GetStdHandle(STD_ERROR_HANDLE);
985 flags[2] |= WX_OPEN;
987 #undef WX_OPEN
992 /******************************************************************************
993 * WCMD_run_program
995 * Execute a command line as an external program. Must allow recursion.
997 * Precedence:
998 * Manual testing under windows shows PATHEXT plays a key part in this,
999 * and the search algorithm and precedence appears to be as follows.
1001 * Search locations:
1002 * If directory supplied on command, just use that directory
1003 * If extension supplied on command, look for that explicit name first
1004 * Otherwise, search in each directory on the path
1005 * Precedence:
1006 * If extension supplied on command, look for that explicit name first
1007 * Then look for supplied name .* (even if extension supplied, so
1008 * 'garbage.exe' will match 'garbage.exe.cmd')
1009 * If any found, cycle through PATHEXT looking for name.exe one by one
1010 * Launching
1011 * Once a match has been found, it is launched - Code currently uses
1012 * findexecutable to achieve this which is left untouched.
1015 void WCMD_run_program (WCHAR *command, int called) {
1017 WCHAR temp[MAX_PATH];
1018 WCHAR pathtosearch[MAXSTRING];
1019 WCHAR *pathposn;
1020 WCHAR stemofsearch[MAX_PATH]; /* maximum allowed executable name is
1021 MAX_PATH, including null character */
1022 WCHAR *lastSlash;
1023 WCHAR pathext[MAXSTRING];
1024 BOOL extensionsupplied = FALSE;
1025 BOOL launched = FALSE;
1026 BOOL status;
1027 BOOL assumeInternal = FALSE;
1028 DWORD len;
1029 static const WCHAR envPath[] = {'P','A','T','H','\0'};
1030 static const WCHAR envPathExt[] = {'P','A','T','H','E','X','T','\0'};
1031 static const WCHAR delims[] = {'/','\\',':','\0'};
1033 WCMD_parse (command, quals, param1, param2); /* Quick way to get the filename */
1034 if (!(*param1) && !(*param2))
1035 return;
1037 /* Calculate the search path and stem to search for */
1038 if (strpbrkW (param1, delims) == NULL) { /* No explicit path given, search path */
1039 static const WCHAR curDir[] = {'.',';','\0'};
1040 strcpyW(pathtosearch, curDir);
1041 len = GetEnvironmentVariableW(envPath, &pathtosearch[2], (sizeof(pathtosearch)/sizeof(WCHAR))-2);
1042 if ((len == 0) || (len >= (sizeof(pathtosearch)/sizeof(WCHAR)) - 2)) {
1043 static const WCHAR curDir[] = {'.','\0'};
1044 strcpyW (pathtosearch, curDir);
1046 if (strchrW(param1, '.') != NULL) extensionsupplied = TRUE;
1047 if (strlenW(param1) >= MAX_PATH)
1049 WCMD_output_asis_stderr(WCMD_LoadMessage(WCMD_LINETOOLONG));
1050 return;
1053 strcpyW(stemofsearch, param1);
1055 } else {
1057 /* Convert eg. ..\fred to include a directory by removing file part */
1058 GetFullPathNameW(param1, sizeof(pathtosearch)/sizeof(WCHAR), pathtosearch, NULL);
1059 lastSlash = strrchrW(pathtosearch, '\\');
1060 if (lastSlash && strchrW(lastSlash, '.') != NULL) extensionsupplied = TRUE;
1061 strcpyW(stemofsearch, lastSlash+1);
1063 /* Reduce pathtosearch to a path with trailing '\' to support c:\a.bat and
1064 c:\windows\a.bat syntax */
1065 if (lastSlash) *(lastSlash + 1) = 0x00;
1068 /* Now extract PATHEXT */
1069 len = GetEnvironmentVariableW(envPathExt, pathext, sizeof(pathext)/sizeof(WCHAR));
1070 if ((len == 0) || (len >= (sizeof(pathext)/sizeof(WCHAR)))) {
1071 static const WCHAR dfltPathExt[] = {'.','b','a','t',';',
1072 '.','c','o','m',';',
1073 '.','c','m','d',';',
1074 '.','e','x','e','\0'};
1075 strcpyW (pathext, dfltPathExt);
1078 /* Loop through the search path, dir by dir */
1079 pathposn = pathtosearch;
1080 WINE_TRACE("Searching in '%s' for '%s'\n", wine_dbgstr_w(pathtosearch),
1081 wine_dbgstr_w(stemofsearch));
1082 while (!launched && pathposn) {
1084 WCHAR thisDir[MAX_PATH] = {'\0'};
1085 WCHAR *pos = NULL;
1086 BOOL found = FALSE;
1088 /* Work on the first directory on the search path */
1089 pos = strchrW(pathposn, ';');
1090 if (pos) {
1091 memcpy(thisDir, pathposn, (pos-pathposn) * sizeof(WCHAR));
1092 thisDir[(pos-pathposn)] = 0x00;
1093 pathposn = pos+1;
1095 } else {
1096 strcpyW(thisDir, pathposn);
1097 pathposn = NULL;
1100 /* Since you can have eg. ..\.. on the path, need to expand
1101 to full information */
1102 strcpyW(temp, thisDir);
1103 GetFullPathNameW(temp, MAX_PATH, thisDir, NULL);
1105 /* 1. If extension supplied, see if that file exists */
1106 strcatW(thisDir, slashW);
1107 strcatW(thisDir, stemofsearch);
1108 pos = &thisDir[strlenW(thisDir)]; /* Pos = end of name */
1110 /* 1. If extension supplied, see if that file exists */
1111 if (extensionsupplied) {
1112 if (GetFileAttributesW(thisDir) != INVALID_FILE_ATTRIBUTES) {
1113 found = TRUE;
1117 /* 2. Any .* matches? */
1118 if (!found) {
1119 HANDLE h;
1120 WIN32_FIND_DATAW finddata;
1121 static const WCHAR allFiles[] = {'.','*','\0'};
1123 strcatW(thisDir,allFiles);
1124 h = FindFirstFileW(thisDir, &finddata);
1125 FindClose(h);
1126 if (h != INVALID_HANDLE_VALUE) {
1128 WCHAR *thisExt = pathext;
1130 /* 3. Yes - Try each path ext */
1131 while (thisExt) {
1132 WCHAR *nextExt = strchrW(thisExt, ';');
1134 if (nextExt) {
1135 memcpy(pos, thisExt, (nextExt-thisExt) * sizeof(WCHAR));
1136 pos[(nextExt-thisExt)] = 0x00;
1137 thisExt = nextExt+1;
1138 } else {
1139 strcpyW(pos, thisExt);
1140 thisExt = NULL;
1143 if (GetFileAttributesW(thisDir) != INVALID_FILE_ATTRIBUTES) {
1144 found = TRUE;
1145 thisExt = NULL;
1151 /* Internal programs won't be picked up by this search, so even
1152 though not found, try one last createprocess and wait for it
1153 to complete.
1154 Note: Ideally we could tell between a console app (wait) and a
1155 windows app, but the API's for it fail in this case */
1156 if (!found && pathposn == NULL) {
1157 WINE_TRACE("ASSUMING INTERNAL\n");
1158 assumeInternal = TRUE;
1159 } else {
1160 WINE_TRACE("Found as %s\n", wine_dbgstr_w(thisDir));
1163 /* Once found, launch it */
1164 if (found || assumeInternal) {
1165 STARTUPINFOW st;
1166 PROCESS_INFORMATION pe;
1167 SHFILEINFOW psfi;
1168 DWORD console;
1169 HINSTANCE hinst;
1170 WCHAR *ext = strrchrW( thisDir, '.' );
1171 static const WCHAR batExt[] = {'.','b','a','t','\0'};
1172 static const WCHAR cmdExt[] = {'.','c','m','d','\0'};
1174 launched = TRUE;
1176 /* Special case BAT and CMD */
1177 if (ext && !strcmpiW(ext, batExt)) {
1178 WCMD_batch (thisDir, command, called, NULL, INVALID_HANDLE_VALUE);
1179 return;
1180 } else if (ext && !strcmpiW(ext, cmdExt)) {
1181 WCMD_batch (thisDir, command, called, NULL, INVALID_HANDLE_VALUE);
1182 return;
1183 } else {
1185 /* thisDir contains the file to be launched, but with what?
1186 eg. a.exe will require a.exe to be launched, a.html may be iexplore */
1187 hinst = FindExecutableW (thisDir, NULL, temp);
1188 if ((INT_PTR)hinst < 32)
1189 console = 0;
1190 else
1191 console = SHGetFileInfoW(temp, 0, &psfi, sizeof(psfi), SHGFI_EXETYPE);
1193 ZeroMemory (&st, sizeof(STARTUPINFOW));
1194 st.cb = sizeof(STARTUPINFOW);
1195 init_msvcrt_io_block(&st);
1197 /* Launch the process and if a CUI wait on it to complete
1198 Note: Launching internal wine processes cannot specify a full path to exe */
1199 status = CreateProcessW(assumeInternal?NULL : thisDir,
1200 command, NULL, NULL, TRUE, 0, NULL, NULL, &st, &pe);
1201 if ((opt_c || opt_k) && !opt_s && !status
1202 && GetLastError()==ERROR_FILE_NOT_FOUND && command[0]=='\"') {
1203 /* strip first and last quote WCHARacters and try again */
1204 WCMD_strip_quotes(command);
1205 opt_s=1;
1206 WCMD_run_program(command, called);
1207 return;
1210 if (!status)
1211 break;
1213 if (!assumeInternal && !console) errorlevel = 0;
1214 else
1216 /* Always wait when called in a batch program context */
1217 if (assumeInternal || context || !HIWORD(console)) WaitForSingleObject (pe.hProcess, INFINITE);
1218 GetExitCodeProcess (pe.hProcess, &errorlevel);
1219 if (errorlevel == STILL_ACTIVE) errorlevel = 0;
1221 CloseHandle(pe.hProcess);
1222 CloseHandle(pe.hThread);
1223 return;
1228 /* Not found anywhere - give up */
1229 SetLastError(ERROR_FILE_NOT_FOUND);
1230 WCMD_print_error ();
1232 /* If a command fails to launch, it sets errorlevel 9009 - which
1233 does not seem to have any associated constant definition */
1234 errorlevel = 9009;
1235 return;
1239 /*****************************************************************************
1240 * Process one command. If the command is EXIT this routine does not return.
1241 * We will recurse through here executing batch files.
1243 void WCMD_execute (const WCHAR *command, const WCHAR *redirects,
1244 const WCHAR *forVariable, const WCHAR *forValue,
1245 CMD_LIST **cmdList)
1247 WCHAR *cmd, *p, *redir;
1248 int status, i;
1249 DWORD count, creationDisposition;
1250 HANDLE h;
1251 WCHAR *whichcmd;
1252 SECURITY_ATTRIBUTES sa;
1253 WCHAR *new_cmd = NULL;
1254 WCHAR *new_redir = NULL;
1255 HANDLE old_stdhandles[3] = {GetStdHandle (STD_INPUT_HANDLE),
1256 GetStdHandle (STD_OUTPUT_HANDLE),
1257 GetStdHandle (STD_ERROR_HANDLE)};
1258 DWORD idx_stdhandles[3] = {STD_INPUT_HANDLE,
1259 STD_OUTPUT_HANDLE,
1260 STD_ERROR_HANDLE};
1261 BOOL prev_echo_mode, piped = FALSE;
1263 WINE_TRACE("command on entry:%s (%p), with forVariable '%s'='%s'\n",
1264 wine_dbgstr_w(command), cmdList,
1265 wine_dbgstr_w(forVariable), wine_dbgstr_w(forValue));
1267 /* If the next command is a pipe then we implement pipes by redirecting
1268 the output from this command to a temp file and input into the
1269 next command from that temp file.
1270 FIXME: Use of named pipes would make more sense here as currently this
1271 process has to finish before the next one can start but this requires
1272 a change to not wait for the first app to finish but rather the pipe */
1273 if (cmdList && (*cmdList)->nextcommand &&
1274 (*cmdList)->nextcommand->prevDelim == CMD_PIPE) {
1276 WCHAR temp_path[MAX_PATH];
1277 static const WCHAR cmdW[] = {'C','M','D','\0'};
1279 /* Remember piping is in action */
1280 WINE_TRACE("Output needs to be piped\n");
1281 piped = TRUE;
1283 /* Generate a unique temporary filename */
1284 GetTempPathW(sizeof(temp_path)/sizeof(WCHAR), temp_path);
1285 GetTempFileNameW(temp_path, cmdW, 0, (*cmdList)->nextcommand->pipeFile);
1286 WINE_TRACE("Using temporary file of %s\n",
1287 wine_dbgstr_w((*cmdList)->nextcommand->pipeFile));
1290 /* Move copy of the command onto the heap so it can be expanded */
1291 new_cmd = HeapAlloc( GetProcessHeap(), 0, MAXSTRING * sizeof(WCHAR));
1292 if (!new_cmd)
1294 WINE_ERR("Could not allocate memory for new_cmd\n");
1295 return;
1297 strcpyW(new_cmd, command);
1299 /* Move copy of the redirects onto the heap so it can be expanded */
1300 new_redir = HeapAlloc( GetProcessHeap(), 0, MAXSTRING * sizeof(WCHAR));
1301 if (!new_redir)
1303 WINE_ERR("Could not allocate memory for new_redir\n");
1304 HeapFree( GetProcessHeap(), 0, new_cmd );
1305 return;
1308 /* If piped output, send stdout to the pipe by appending >filename to redirects */
1309 if (piped) {
1310 static const WCHAR redirOut[] = {'%','s',' ','>',' ','%','s','\0'};
1311 wsprintfW (new_redir, redirOut, redirects, (*cmdList)->nextcommand->pipeFile);
1312 WINE_TRACE("Redirects now %s\n", wine_dbgstr_w(new_redir));
1313 } else {
1314 strcpyW(new_redir, redirects);
1317 /* Expand variables in command line mode only (batch mode will
1318 be expanded as the line is read in, except for 'for' loops) */
1319 handleExpansion(new_cmd, (context != NULL), forVariable, forValue);
1320 handleExpansion(new_redir, (context != NULL), forVariable, forValue);
1321 cmd = new_cmd;
1324 * Changing default drive has to be handled as a special case.
1327 if ((cmd[1] == ':') && IsCharAlphaW(cmd[0]) && (strlenW(cmd) == 2)) {
1328 WCHAR envvar[5];
1329 WCHAR dir[MAX_PATH];
1331 /* According to MSDN CreateProcess docs, special env vars record
1332 the current directory on each drive, in the form =C:
1333 so see if one specified, and if so go back to it */
1334 strcpyW(envvar, equalW);
1335 strcatW(envvar, cmd);
1336 if (GetEnvironmentVariableW(envvar, dir, MAX_PATH) == 0) {
1337 static const WCHAR fmt[] = {'%','s','\\','\0'};
1338 wsprintfW(cmd, fmt, cmd);
1339 WINE_TRACE("No special directory settings, using dir of %s\n", wine_dbgstr_w(cmd));
1341 WINE_TRACE("Got directory %s as %s\n", wine_dbgstr_w(envvar), wine_dbgstr_w(cmd));
1342 status = SetCurrentDirectoryW(cmd);
1343 if (!status) WCMD_print_error ();
1344 HeapFree( GetProcessHeap(), 0, cmd );
1345 HeapFree( GetProcessHeap(), 0, new_redir );
1346 return;
1349 sa.nLength = sizeof(sa);
1350 sa.lpSecurityDescriptor = NULL;
1351 sa.bInheritHandle = TRUE;
1354 * Redirect stdin, stdout and/or stderr if required.
1357 /* STDIN could come from a preceding pipe, so delete on close if it does */
1358 if (cmdList && (*cmdList)->pipeFile[0] != 0x00) {
1359 WINE_TRACE("Input coming from %s\n", wine_dbgstr_w((*cmdList)->pipeFile));
1360 h = CreateFileW((*cmdList)->pipeFile, GENERIC_READ,
1361 FILE_SHARE_READ, &sa, OPEN_EXISTING,
1362 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE, NULL);
1363 if (h == INVALID_HANDLE_VALUE) {
1364 WCMD_print_error ();
1365 HeapFree( GetProcessHeap(), 0, cmd );
1366 HeapFree( GetProcessHeap(), 0, new_redir );
1367 return;
1369 SetStdHandle (STD_INPUT_HANDLE, h);
1371 /* No need to remember the temporary name any longer once opened */
1372 (*cmdList)->pipeFile[0] = 0x00;
1374 /* Otherwise STDIN could come from a '<' redirect */
1375 } else if ((p = strchrW(new_redir,'<')) != NULL) {
1376 h = CreateFileW(WCMD_parameter(++p, 0, NULL, NULL), GENERIC_READ, FILE_SHARE_READ,
1377 &sa, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
1378 if (h == INVALID_HANDLE_VALUE) {
1379 WCMD_print_error ();
1380 HeapFree( GetProcessHeap(), 0, cmd );
1381 HeapFree( GetProcessHeap(), 0, new_redir );
1382 return;
1384 SetStdHandle (STD_INPUT_HANDLE, h);
1387 /* Scan the whole command looking for > and 2> */
1388 redir = new_redir;
1389 while (redir != NULL && ((p = strchrW(redir,'>')) != NULL)) {
1390 int handle = 0;
1392 if (p > redir && (*(p-1)=='2'))
1393 handle = 2;
1394 else
1395 handle = 1;
1397 p++;
1398 if ('>' == *p) {
1399 creationDisposition = OPEN_ALWAYS;
1400 p++;
1402 else {
1403 creationDisposition = CREATE_ALWAYS;
1406 /* Add support for 2>&1 */
1407 redir = p;
1408 if (*p == '&') {
1409 int idx = *(p+1) - '0';
1411 if (DuplicateHandle(GetCurrentProcess(),
1412 GetStdHandle(idx_stdhandles[idx]),
1413 GetCurrentProcess(),
1415 0, TRUE, DUPLICATE_SAME_ACCESS) == 0) {
1416 WINE_FIXME("Duplicating handle failed with gle %d\n", GetLastError());
1418 WINE_TRACE("Redirect %d (%p) to %d (%p)\n", handle, GetStdHandle(idx_stdhandles[idx]), idx, h);
1420 } else {
1421 WCHAR *param = WCMD_parameter(p, 0, NULL, NULL);
1422 h = CreateFileW(param, GENERIC_WRITE, 0, &sa, creationDisposition,
1423 FILE_ATTRIBUTE_NORMAL, NULL);
1424 if (h == INVALID_HANDLE_VALUE) {
1425 WCMD_print_error ();
1426 HeapFree( GetProcessHeap(), 0, cmd );
1427 HeapFree( GetProcessHeap(), 0, new_redir );
1428 return;
1430 if (SetFilePointer (h, 0, NULL, FILE_END) ==
1431 INVALID_SET_FILE_POINTER) {
1432 WCMD_print_error ();
1434 WINE_TRACE("Redirect %d to '%s' (%p)\n", handle, wine_dbgstr_w(param), h);
1437 SetStdHandle (idx_stdhandles[handle], h);
1441 * Strip leading whitespaces, and a '@' if supplied
1443 whichcmd = WCMD_skip_leading_spaces(cmd);
1444 WINE_TRACE("Command: '%s'\n", wine_dbgstr_w(cmd));
1445 if (whichcmd[0] == '@') whichcmd++;
1448 * Check if the command entered is internal. If it is, pass the rest of the
1449 * line down to the command. If not try to run a program.
1452 count = 0;
1453 while (IsCharAlphaNumericW(whichcmd[count])) {
1454 count++;
1456 for (i=0; i<=WCMD_EXIT; i++) {
1457 if (CompareStringW(LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
1458 whichcmd, count, inbuilt[i], -1) == CSTR_EQUAL) break;
1460 p = WCMD_skip_leading_spaces (&whichcmd[count]);
1461 WCMD_parse (p, quals, param1, param2);
1462 WINE_TRACE("param1: %s, param2: %s\n", wine_dbgstr_w(param1), wine_dbgstr_w(param2));
1464 if (i <= WCMD_EXIT && (p[0] == '/') && (p[1] == '?')) {
1465 /* this is a help request for a builtin program */
1466 i = WCMD_HELP;
1467 memcpy(p, whichcmd, count * sizeof(WCHAR));
1468 p[count] = '\0';
1472 switch (i) {
1474 case WCMD_CALL:
1475 WCMD_call (p);
1476 break;
1477 case WCMD_CD:
1478 case WCMD_CHDIR:
1479 WCMD_setshow_default (p);
1480 break;
1481 case WCMD_CLS:
1482 WCMD_clear_screen ();
1483 break;
1484 case WCMD_COPY:
1485 WCMD_copy ();
1486 break;
1487 case WCMD_CTTY:
1488 WCMD_change_tty ();
1489 break;
1490 case WCMD_DATE:
1491 WCMD_setshow_date ();
1492 break;
1493 case WCMD_DEL:
1494 case WCMD_ERASE:
1495 WCMD_delete (p);
1496 break;
1497 case WCMD_DIR:
1498 WCMD_directory (p);
1499 break;
1500 case WCMD_ECHO:
1501 WCMD_echo(&whichcmd[count]);
1502 break;
1503 case WCMD_FOR:
1504 WCMD_for (p, cmdList);
1505 break;
1506 case WCMD_GOTO:
1507 WCMD_goto (cmdList);
1508 break;
1509 case WCMD_HELP:
1510 WCMD_give_help (p);
1511 break;
1512 case WCMD_IF:
1513 WCMD_if (p, cmdList);
1514 break;
1515 case WCMD_LABEL:
1516 WCMD_volume (TRUE, p);
1517 break;
1518 case WCMD_MD:
1519 case WCMD_MKDIR:
1520 WCMD_create_dir (p);
1521 break;
1522 case WCMD_MOVE:
1523 WCMD_move ();
1524 break;
1525 case WCMD_PATH:
1526 WCMD_setshow_path (p);
1527 break;
1528 case WCMD_PAUSE:
1529 WCMD_pause ();
1530 break;
1531 case WCMD_PROMPT:
1532 WCMD_setshow_prompt ();
1533 break;
1534 case WCMD_REM:
1535 break;
1536 case WCMD_REN:
1537 case WCMD_RENAME:
1538 WCMD_rename ();
1539 break;
1540 case WCMD_RD:
1541 case WCMD_RMDIR:
1542 WCMD_remove_dir (p);
1543 break;
1544 case WCMD_SETLOCAL:
1545 WCMD_setlocal(p);
1546 break;
1547 case WCMD_ENDLOCAL:
1548 WCMD_endlocal();
1549 break;
1550 case WCMD_SET:
1551 WCMD_setshow_env (p);
1552 break;
1553 case WCMD_SHIFT:
1554 WCMD_shift (p);
1555 break;
1556 case WCMD_TIME:
1557 WCMD_setshow_time ();
1558 break;
1559 case WCMD_TITLE:
1560 if (strlenW(&whichcmd[count]) > 0)
1561 WCMD_title(&whichcmd[count+1]);
1562 break;
1563 case WCMD_TYPE:
1564 WCMD_type (p);
1565 break;
1566 case WCMD_VER:
1567 WCMD_output(newline);
1568 WCMD_version ();
1569 break;
1570 case WCMD_VERIFY:
1571 WCMD_verify (p);
1572 break;
1573 case WCMD_VOL:
1574 WCMD_volume (FALSE, p);
1575 break;
1576 case WCMD_PUSHD:
1577 WCMD_pushd(p);
1578 break;
1579 case WCMD_POPD:
1580 WCMD_popd();
1581 break;
1582 case WCMD_ASSOC:
1583 WCMD_assoc(p, TRUE);
1584 break;
1585 case WCMD_COLOR:
1586 WCMD_color();
1587 break;
1588 case WCMD_FTYPE:
1589 WCMD_assoc(p, FALSE);
1590 break;
1591 case WCMD_MORE:
1592 WCMD_more(p);
1593 break;
1594 case WCMD_CHOICE:
1595 WCMD_choice(p);
1596 break;
1597 case WCMD_EXIT:
1598 WCMD_exit (cmdList);
1599 break;
1600 default:
1601 prev_echo_mode = echo_mode;
1602 WCMD_run_program (whichcmd, 0);
1603 echo_mode = prev_echo_mode;
1605 HeapFree( GetProcessHeap(), 0, cmd );
1606 HeapFree( GetProcessHeap(), 0, new_redir );
1608 /* Restore old handles */
1609 for (i=0; i<3; i++) {
1610 if (old_stdhandles[i] != GetStdHandle(idx_stdhandles[i])) {
1611 CloseHandle (GetStdHandle (idx_stdhandles[i]));
1612 SetStdHandle (idx_stdhandles[i], old_stdhandles[i]);
1617 /*************************************************************************
1618 * WCMD_LoadMessage
1619 * Load a string from the resource file, handling any error
1620 * Returns string retrieved from resource file
1622 WCHAR *WCMD_LoadMessage(UINT id) {
1623 static WCHAR msg[2048];
1624 static const WCHAR failedMsg[] = {'F','a','i','l','e','d','!','\0'};
1626 if (!LoadStringW(GetModuleHandleW(NULL), id, msg, sizeof(msg)/sizeof(WCHAR))) {
1627 WINE_FIXME("LoadString failed with %d\n", GetLastError());
1628 strcpyW(msg, failedMsg);
1630 return msg;
1633 /***************************************************************************
1634 * WCMD_DumpCommands
1636 * Dumps out the parsed command line to ensure syntax is correct
1638 static void WCMD_DumpCommands(CMD_LIST *commands) {
1639 CMD_LIST *thisCmd = commands;
1641 WINE_TRACE("Parsed line:\n");
1642 while (thisCmd != NULL) {
1643 WINE_TRACE("%p %d %2.2d %p %s Redir:%s\n",
1644 thisCmd,
1645 thisCmd->prevDelim,
1646 thisCmd->bracketDepth,
1647 thisCmd->nextcommand,
1648 wine_dbgstr_w(thisCmd->command),
1649 wine_dbgstr_w(thisCmd->redirects));
1650 thisCmd = thisCmd->nextcommand;
1654 /***************************************************************************
1655 * WCMD_addCommand
1657 * Adds a command to the current command list
1659 static void WCMD_addCommand(WCHAR *command, int *commandLen,
1660 WCHAR *redirs, int *redirLen,
1661 WCHAR **copyTo, int **copyToLen,
1662 CMD_DELIMITERS prevDelim, int curDepth,
1663 CMD_LIST **lastEntry, CMD_LIST **output) {
1665 CMD_LIST *thisEntry = NULL;
1667 /* Allocate storage for command */
1668 thisEntry = HeapAlloc(GetProcessHeap(), 0, sizeof(CMD_LIST));
1670 /* Copy in the command */
1671 if (command) {
1672 thisEntry->command = HeapAlloc(GetProcessHeap(), 0,
1673 (*commandLen+1) * sizeof(WCHAR));
1674 memcpy(thisEntry->command, command, *commandLen * sizeof(WCHAR));
1675 thisEntry->command[*commandLen] = 0x00;
1677 /* Copy in the redirects */
1678 thisEntry->redirects = HeapAlloc(GetProcessHeap(), 0,
1679 (*redirLen+1) * sizeof(WCHAR));
1680 memcpy(thisEntry->redirects, redirs, *redirLen * sizeof(WCHAR));
1681 thisEntry->redirects[*redirLen] = 0x00;
1682 thisEntry->pipeFile[0] = 0x00;
1684 /* Reset the lengths */
1685 *commandLen = 0;
1686 *redirLen = 0;
1687 *copyToLen = commandLen;
1688 *copyTo = command;
1690 } else {
1691 thisEntry->command = NULL;
1692 thisEntry->redirects = NULL;
1693 thisEntry->pipeFile[0] = 0x00;
1696 /* Fill in other fields */
1697 thisEntry->nextcommand = NULL;
1698 thisEntry->prevDelim = prevDelim;
1699 thisEntry->bracketDepth = curDepth;
1700 if (*lastEntry) {
1701 (*lastEntry)->nextcommand = thisEntry;
1702 } else {
1703 *output = thisEntry;
1705 *lastEntry = thisEntry;
1709 /***************************************************************************
1710 * WCMD_IsEndQuote
1712 * Checks if the quote pointed to is the end-quote.
1714 * Quotes end if:
1716 * 1) The current parameter ends at EOL or at the beginning
1717 * of a redirection or pipe and not in a quote section.
1719 * 2) If the next character is a space and not in a quote section.
1721 * Returns TRUE if this is an end quote, and FALSE if it is not.
1724 static BOOL WCMD_IsEndQuote(const WCHAR *quote, int quoteIndex)
1726 int quoteCount = quoteIndex;
1727 int i;
1729 /* If we are not in a quoted section, then we are not an end-quote */
1730 if(quoteIndex == 0)
1732 return FALSE;
1735 /* Check how many quotes are left for this parameter */
1736 for(i=0;quote[i];i++)
1738 if(quote[i] == '"')
1740 quoteCount++;
1743 /* Quote counting ends at EOL, redirection, space or pipe if current quote is complete */
1744 else if(((quoteCount % 2) == 0)
1745 && ((quote[i] == '<') || (quote[i] == '>') || (quote[i] == '|') || (quote[i] == ' ')))
1747 break;
1751 /* If the quote is part of the last part of a series of quotes-on-quotes, then it must
1752 be an end-quote */
1753 if(quoteIndex >= (quoteCount / 2))
1755 return TRUE;
1758 /* No cigar */
1759 return FALSE;
1762 /***************************************************************************
1763 * WCMD_ReadAndParseLine
1765 * Either uses supplied input or
1766 * Reads a file from the handle, and then...
1767 * Parse the text buffer, splitting into separate commands
1768 * - unquoted && strings split 2 commands but the 2nd is flagged as
1769 * following an &&
1770 * - ( as the first character just ups the bracket depth
1771 * - unquoted ) when bracket depth > 0 terminates a bracket and
1772 * adds a CMD_LIST structure with null command
1773 * - Anything else gets put into the command string (including
1774 * redirects)
1776 WCHAR *WCMD_ReadAndParseLine(const WCHAR *optionalcmd, CMD_LIST **output, HANDLE readFrom)
1778 WCHAR *curPos;
1779 int inQuotes = 0;
1780 WCHAR curString[MAXSTRING];
1781 int curStringLen = 0;
1782 WCHAR curRedirs[MAXSTRING];
1783 int curRedirsLen = 0;
1784 WCHAR *curCopyTo;
1785 int *curLen;
1786 int curDepth = 0;
1787 CMD_LIST *lastEntry = NULL;
1788 CMD_DELIMITERS prevDelim = CMD_NONE;
1789 static WCHAR *extraSpace = NULL; /* Deliberately never freed */
1790 static const WCHAR remCmd[] = {'r','e','m'};
1791 static const WCHAR forCmd[] = {'f','o','r'};
1792 static const WCHAR ifCmd[] = {'i','f'};
1793 static const WCHAR ifElse[] = {'e','l','s','e'};
1794 BOOL inRem = FALSE;
1795 BOOL inFor = FALSE;
1796 BOOL inIn = FALSE;
1797 BOOL inIf = FALSE;
1798 BOOL inElse= FALSE;
1799 BOOL onlyWhiteSpace = FALSE;
1800 BOOL lastWasWhiteSpace = FALSE;
1801 BOOL lastWasDo = FALSE;
1802 BOOL lastWasIn = FALSE;
1803 BOOL lastWasElse = FALSE;
1804 BOOL lastWasRedirect = TRUE;
1806 /* Allocate working space for a command read from keyboard, file etc */
1807 if (!extraSpace)
1808 extraSpace = HeapAlloc(GetProcessHeap(), 0, (MAXSTRING+1) * sizeof(WCHAR));
1809 if (!extraSpace)
1811 WINE_ERR("Could not allocate memory for extraSpace\n");
1812 return NULL;
1815 /* If initial command read in, use that, otherwise get input from handle */
1816 if (optionalcmd != NULL) {
1817 strcpyW(extraSpace, optionalcmd);
1818 } else if (readFrom == INVALID_HANDLE_VALUE) {
1819 WINE_FIXME("No command nor handle supplied\n");
1820 } else {
1821 if (!WCMD_fgets(extraSpace, MAXSTRING, readFrom))
1822 return NULL;
1824 curPos = extraSpace;
1826 /* Handle truncated input - issue warning */
1827 if (strlenW(extraSpace) == MAXSTRING -1) {
1828 WCMD_output_asis_stderr(WCMD_LoadMessage(WCMD_TRUNCATEDLINE));
1829 WCMD_output_asis_stderr(extraSpace);
1830 WCMD_output_asis_stderr(newline);
1833 /* Replace env vars if in a batch context */
1834 if (context) handleExpansion(extraSpace, FALSE, NULL, NULL);
1835 /* Show prompt before batch line IF echo is on and in batch program */
1836 if (context && echo_mode && extraSpace[0] && (extraSpace[0] != '@')) {
1837 static const WCHAR echoDot[] = {'e','c','h','o','.'};
1838 static const WCHAR echoCol[] = {'e','c','h','o',':'};
1839 const DWORD len = sizeof(echoDot)/sizeof(echoDot[0]);
1840 DWORD curr_size = strlenW(extraSpace);
1841 DWORD min_len = (curr_size < len ? curr_size : len);
1842 WCMD_show_prompt();
1843 WCMD_output_asis(extraSpace);
1844 /* I don't know why Windows puts a space here but it does */
1845 /* Except for lines starting with 'echo.' or 'echo:'. Ask MS why */
1846 if (CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
1847 extraSpace, min_len, echoDot, len) != CSTR_EQUAL
1848 && CompareStringW(LOCALE_SYSTEM_DEFAULT, NORM_IGNORECASE,
1849 extraSpace, min_len, echoCol, len) != CSTR_EQUAL)
1851 WCMD_output_asis(space);
1853 WCMD_output_asis(newline);
1856 /* Start with an empty string, copying to the command string */
1857 curStringLen = 0;
1858 curRedirsLen = 0;
1859 curCopyTo = curString;
1860 curLen = &curStringLen;
1861 lastWasRedirect = FALSE; /* Required for eg spaces between > and filename */
1863 /* Parse every character on the line being processed */
1864 while (*curPos != 0x00) {
1866 WCHAR thisChar;
1868 /* Debugging AID:
1869 WINE_TRACE("Looking at '%c' (len:%d, lws:%d, ows:%d)\n", *curPos, *curLen,
1870 lastWasWhiteSpace, onlyWhiteSpace);
1873 /* Certain commands need special handling */
1874 if (curStringLen == 0 && curCopyTo == curString) {
1875 static const WCHAR forDO[] = {'d','o'};
1877 /* If command starts with 'rem ', ignore any &&, ( etc. */
1878 if (WCMD_keyword_ws_found(remCmd, sizeof(remCmd)/sizeof(remCmd[0]), curPos)) {
1879 inRem = TRUE;
1881 } else if (WCMD_keyword_ws_found(forCmd, sizeof(forCmd)/sizeof(forCmd[0]), curPos)) {
1882 inFor = TRUE;
1884 /* If command starts with 'if ' or 'else ', handle ('s mid line. We should ensure this
1885 is only true in the command portion of the IF statement, but this
1886 should suffice for now
1887 FIXME: Silly syntax like "if 1(==1( (
1888 echo they equal
1889 )" will be parsed wrong */
1890 } else if (WCMD_keyword_ws_found(ifCmd, sizeof(ifCmd)/sizeof(ifCmd[0]), curPos)) {
1891 inIf = TRUE;
1893 } else if (WCMD_keyword_ws_found(ifElse, sizeof(ifElse)/sizeof(ifElse[0]), curPos)) {
1894 const int keyw_len = sizeof(ifElse)/sizeof(ifElse[0]) + 1;
1895 inElse = TRUE;
1896 lastWasElse = TRUE;
1897 onlyWhiteSpace = TRUE;
1898 memcpy(&curCopyTo[*curLen], curPos, keyw_len*sizeof(WCHAR));
1899 (*curLen)+=keyw_len;
1900 curPos+=keyw_len;
1901 continue;
1903 /* In a for loop, the DO command will follow a close bracket followed by
1904 whitespace, followed by DO, ie closeBracket inserts a NULL entry, curLen
1905 is then 0, and all whitespace is skipped */
1906 } else if (inFor &&
1907 WCMD_keyword_ws_found(forDO, sizeof(forDO)/sizeof(forDO[0]), curPos)) {
1908 const int keyw_len = sizeof(forDO)/sizeof(forDO[0]) + 1;
1909 WINE_TRACE("Found 'DO '\n");
1910 lastWasDo = TRUE;
1911 onlyWhiteSpace = TRUE;
1912 memcpy(&curCopyTo[*curLen], curPos, keyw_len*sizeof(WCHAR));
1913 (*curLen)+=keyw_len;
1914 curPos+=keyw_len;
1915 continue;
1917 } else if (curCopyTo == curString) {
1919 /* Special handling for the 'FOR' command */
1920 if (inFor && lastWasWhiteSpace) {
1921 static const WCHAR forIN[] = {'i','n'};
1923 WINE_TRACE("Found 'FOR ', comparing next parm: '%s'\n", wine_dbgstr_w(curPos));
1925 if (WCMD_keyword_ws_found(forIN, sizeof(forIN)/sizeof(forIN[0]), curPos)) {
1926 const int keyw_len = sizeof(forIN)/sizeof(forIN[0]) + 1;
1927 WINE_TRACE("Found 'IN '\n");
1928 lastWasIn = TRUE;
1929 onlyWhiteSpace = TRUE;
1930 memcpy(&curCopyTo[*curLen], curPos, keyw_len*sizeof(WCHAR));
1931 (*curLen)+=keyw_len;
1932 curPos+=keyw_len;
1933 continue;
1938 /* Nothing 'ends' a REM statement and &&, quotes etc are ineffective,
1939 so just use the default processing ie skip character specific
1940 matching below */
1941 if (!inRem) thisChar = *curPos;
1942 else thisChar = 'X'; /* Character with no special processing */
1944 lastWasWhiteSpace = FALSE; /* Will be reset below */
1946 switch (thisChar) {
1948 case '=': /* drop through - ignore token delimiters at the start of a command */
1949 case ',': /* drop through - ignore token delimiters at the start of a command */
1950 case '\t':/* drop through - ignore token delimiters at the start of a command */
1951 case ' ':
1952 /* If a redirect in place, it ends here */
1953 if (!inQuotes && !lastWasRedirect) {
1955 /* If finishing off a redirect, add a whitespace delimiter */
1956 if (curCopyTo == curRedirs) {
1957 curCopyTo[(*curLen)++] = ' ';
1959 curCopyTo = curString;
1960 curLen = &curStringLen;
1962 if (*curLen > 0) {
1963 curCopyTo[(*curLen)++] = *curPos;
1966 /* Remember just processed whitespace */
1967 lastWasWhiteSpace = TRUE;
1969 break;
1971 case '>': /* drop through - handle redirect chars the same */
1972 case '<':
1973 /* Make a redirect start here */
1974 if (!inQuotes) {
1975 curCopyTo = curRedirs;
1976 curLen = &curRedirsLen;
1977 lastWasRedirect = TRUE;
1980 /* See if 1>, 2> etc, in which case we have some patching up
1981 to do (provided there's a preceding whitespace, and enough
1982 chars read so far) */
1983 if (curStringLen > 2
1984 && (*(curPos-1)>='1') && (*(curPos-1)<='9')
1985 && ((*(curPos-2)==' ') || (*(curPos-2)=='\t'))) {
1986 curStringLen--;
1987 curString[curStringLen] = 0x00;
1988 curCopyTo[(*curLen)++] = *(curPos-1);
1991 curCopyTo[(*curLen)++] = *curPos;
1993 /* If a redirect is immediately followed by '&' (ie. 2>&1) then
1994 do not process that ampersand as an AND operator */
1995 if (thisChar == '>' && *(curPos+1) == '&') {
1996 curCopyTo[(*curLen)++] = *(curPos+1);
1997 curPos++;
1999 break;
2001 case '|': /* Pipe character only if not || */
2002 if (!inQuotes) {
2003 lastWasRedirect = FALSE;
2005 /* Add an entry to the command list */
2006 if (curStringLen > 0) {
2008 /* Add the current command */
2009 WCMD_addCommand(curString, &curStringLen,
2010 curRedirs, &curRedirsLen,
2011 &curCopyTo, &curLen,
2012 prevDelim, curDepth,
2013 &lastEntry, output);
2017 if (*(curPos+1) == '|') {
2018 curPos++; /* Skip other | */
2019 prevDelim = CMD_ONFAILURE;
2020 } else {
2021 prevDelim = CMD_PIPE;
2023 } else {
2024 curCopyTo[(*curLen)++] = *curPos;
2026 break;
2028 case '"': if (WCMD_IsEndQuote(curPos, inQuotes)) {
2029 inQuotes--;
2030 } else {
2031 inQuotes++; /* Quotes within quotes are fun! */
2033 curCopyTo[(*curLen)++] = *curPos;
2034 lastWasRedirect = FALSE;
2035 break;
2037 case '(': /* If a '(' is the first non whitespace in a command portion
2038 ie start of line or just after &&, then we read until an
2039 unquoted ) is found */
2040 WINE_TRACE("Found '(' conditions: curLen(%d), inQ(%d), onlyWS(%d)"
2041 ", for(%d, In:%d, Do:%d)"
2042 ", if(%d, else:%d, lwe:%d)\n",
2043 *curLen, inQuotes,
2044 onlyWhiteSpace,
2045 inFor, lastWasIn, lastWasDo,
2046 inIf, inElse, lastWasElse);
2047 lastWasRedirect = FALSE;
2049 /* Ignore open brackets inside the for set */
2050 if (*curLen == 0 && !inIn) {
2051 curDepth++;
2053 /* If in quotes, ignore brackets */
2054 } else if (inQuotes) {
2055 curCopyTo[(*curLen)++] = *curPos;
2057 /* In a FOR loop, an unquoted '(' may occur straight after
2058 IN or DO
2059 In an IF statement just handle it regardless as we don't
2060 parse the operands
2061 In an ELSE statement, only allow it straight away after
2062 the ELSE and whitespace
2064 } else if (inIf ||
2065 (inElse && lastWasElse && onlyWhiteSpace) ||
2066 (inFor && (lastWasIn || lastWasDo) && onlyWhiteSpace)) {
2068 /* If entering into an 'IN', set inIn */
2069 if (inFor && lastWasIn && onlyWhiteSpace) {
2070 WINE_TRACE("Inside an IN\n");
2071 inIn = TRUE;
2074 /* Add the current command */
2075 WCMD_addCommand(curString, &curStringLen,
2076 curRedirs, &curRedirsLen,
2077 &curCopyTo, &curLen,
2078 prevDelim, curDepth,
2079 &lastEntry, output);
2081 curDepth++;
2082 } else {
2083 curCopyTo[(*curLen)++] = *curPos;
2085 break;
2087 case '&': if (!inQuotes) {
2088 lastWasRedirect = FALSE;
2090 /* Add an entry to the command list */
2091 if (curStringLen > 0) {
2093 /* Add the current command */
2094 WCMD_addCommand(curString, &curStringLen,
2095 curRedirs, &curRedirsLen,
2096 &curCopyTo, &curLen,
2097 prevDelim, curDepth,
2098 &lastEntry, output);
2102 if (*(curPos+1) == '&') {
2103 curPos++; /* Skip other & */
2104 prevDelim = CMD_ONSUCCESS;
2105 } else {
2106 prevDelim = CMD_NONE;
2108 } else {
2109 curCopyTo[(*curLen)++] = *curPos;
2111 break;
2113 case ')': if (!inQuotes && curDepth > 0) {
2114 lastWasRedirect = FALSE;
2116 /* Add the current command if there is one */
2117 if (curStringLen) {
2119 /* Add the current command */
2120 WCMD_addCommand(curString, &curStringLen,
2121 curRedirs, &curRedirsLen,
2122 &curCopyTo, &curLen,
2123 prevDelim, curDepth,
2124 &lastEntry, output);
2127 /* Add an empty entry to the command list */
2128 prevDelim = CMD_NONE;
2129 WCMD_addCommand(NULL, &curStringLen,
2130 curRedirs, &curRedirsLen,
2131 &curCopyTo, &curLen,
2132 prevDelim, curDepth,
2133 &lastEntry, output);
2134 curDepth--;
2136 /* Leave inIn if necessary */
2137 if (inIn) inIn = FALSE;
2138 } else {
2139 curCopyTo[(*curLen)++] = *curPos;
2141 break;
2142 default:
2143 lastWasRedirect = FALSE;
2144 curCopyTo[(*curLen)++] = *curPos;
2147 curPos++;
2149 /* At various times we need to know if we have only skipped whitespace,
2150 so reset this variable and then it will remain true until a non
2151 whitespace is found */
2152 if ((thisChar != ' ') && (thisChar != '\t') && (thisChar != '\n'))
2153 onlyWhiteSpace = FALSE;
2155 /* Flag end of interest in FOR DO and IN parms once something has been processed */
2156 if (!lastWasWhiteSpace) {
2157 lastWasIn = lastWasDo = FALSE;
2160 /* If we have reached the end, add this command into the list */
2161 if (*curPos == 0x00 && *curLen > 0) {
2163 /* Add an entry to the command list */
2164 WCMD_addCommand(curString, &curStringLen,
2165 curRedirs, &curRedirsLen,
2166 &curCopyTo, &curLen,
2167 prevDelim, curDepth,
2168 &lastEntry, output);
2171 /* If we have reached the end of the string, see if bracketing outstanding */
2172 if (*curPos == 0x00 && curDepth > 0 && readFrom != INVALID_HANDLE_VALUE) {
2173 inRem = FALSE;
2174 prevDelim = CMD_NONE;
2175 inQuotes = 0;
2176 memset(extraSpace, 0x00, (MAXSTRING+1) * sizeof(WCHAR));
2178 /* Read more, skipping any blank lines */
2179 while (*extraSpace == 0x00) {
2180 if (!context) WCMD_output_asis( WCMD_LoadMessage(WCMD_MOREPROMPT));
2181 if (!WCMD_fgets(extraSpace, MAXSTRING, readFrom))
2182 break;
2184 curPos = extraSpace;
2185 if (context) handleExpansion(extraSpace, FALSE, NULL, NULL);
2186 /* Continue to echo commands IF echo is on and in batch program */
2187 if (context && echo_mode && extraSpace[0] && (extraSpace[0] != '@')) {
2188 WCMD_output_asis(extraSpace);
2189 WCMD_output_asis(newline);
2194 /* Dump out the parsed output */
2195 WCMD_DumpCommands(*output);
2197 return extraSpace;
2200 /***************************************************************************
2201 * WCMD_process_commands
2203 * Process all the commands read in so far
2205 CMD_LIST *WCMD_process_commands(CMD_LIST *thisCmd, BOOL oneBracket,
2206 const WCHAR *var, const WCHAR *val) {
2208 int bdepth = -1;
2210 if (thisCmd && oneBracket) bdepth = thisCmd->bracketDepth;
2212 /* Loop through the commands, processing them one by one */
2213 while (thisCmd) {
2215 CMD_LIST *origCmd = thisCmd;
2217 /* If processing one bracket only, and we find the end bracket
2218 entry (or less), return */
2219 if (oneBracket && !thisCmd->command &&
2220 bdepth <= thisCmd->bracketDepth) {
2221 WINE_TRACE("Finished bracket @ %p, next command is %p\n",
2222 thisCmd, thisCmd->nextcommand);
2223 return thisCmd->nextcommand;
2226 /* Ignore the NULL entries a ')' inserts (Only 'if' cares
2227 about them and it will be handled in there)
2228 Also, skip over any batch labels (eg. :fred) */
2229 if (thisCmd->command && thisCmd->command[0] != ':') {
2230 WINE_TRACE("Executing command: '%s'\n", wine_dbgstr_w(thisCmd->command));
2231 WCMD_execute (thisCmd->command, thisCmd->redirects, var, val, &thisCmd);
2234 /* Step on unless the command itself already stepped on */
2235 if (thisCmd == origCmd) thisCmd = thisCmd->nextcommand;
2237 return NULL;
2240 /***************************************************************************
2241 * WCMD_free_commands
2243 * Frees the storage held for a parsed command line
2244 * - This is not done in the process_commands, as eventually the current
2245 * pointer will be modified within the commands, and hence a single free
2246 * routine is simpler
2248 void WCMD_free_commands(CMD_LIST *cmds) {
2250 /* Loop through the commands, freeing them one by one */
2251 while (cmds) {
2252 CMD_LIST *thisCmd = cmds;
2253 cmds = cmds->nextcommand;
2254 HeapFree(GetProcessHeap(), 0, thisCmd->command);
2255 HeapFree(GetProcessHeap(), 0, thisCmd->redirects);
2256 HeapFree(GetProcessHeap(), 0, thisCmd);
2261 /*****************************************************************************
2262 * Main entry point. This is a console application so we have a main() not a
2263 * winmain().
2266 int wmain (int argc, WCHAR *argvW[])
2268 int args;
2269 WCHAR *cmd = NULL;
2270 WCHAR string[1024];
2271 WCHAR envvar[4];
2272 int opt_q;
2273 int opt_t = 0;
2274 static const WCHAR promptW[] = {'P','R','O','M','P','T','\0'};
2275 static const WCHAR defaultpromptW[] = {'$','P','$','G','\0'};
2276 char ansiVersion[100];
2277 CMD_LIST *toExecute = NULL; /* Commands left to be executed */
2279 srand(time(NULL));
2281 /* Pre initialize some messages */
2282 strcpy(ansiVersion, PACKAGE_VERSION);
2283 MultiByteToWideChar(CP_ACP, 0, ansiVersion, -1, string, 1024);
2284 wsprintfW(version_string, WCMD_LoadMessage(WCMD_VERSION), string);
2285 strcpyW(anykey, WCMD_LoadMessage(WCMD_ANYKEY));
2287 args = argc;
2288 opt_c=opt_k=opt_q=opt_s=0;
2289 while (args > 0)
2291 WCHAR c;
2292 WINE_TRACE("Command line parm: '%s'\n", wine_dbgstr_w(*argvW));
2293 if ((*argvW)[0]!='/' || (*argvW)[1]=='\0') {
2294 argvW++;
2295 args--;
2296 continue;
2299 c=(*argvW)[1];
2300 if (tolowerW(c)=='c') {
2301 opt_c=1;
2302 } else if (tolowerW(c)=='q') {
2303 opt_q=1;
2304 } else if (tolowerW(c)=='k') {
2305 opt_k=1;
2306 } else if (tolowerW(c)=='s') {
2307 opt_s=1;
2308 } else if (tolowerW(c)=='a') {
2309 unicodePipes=FALSE;
2310 } else if (tolowerW(c)=='u') {
2311 unicodePipes=TRUE;
2312 } else if (tolowerW(c)=='t' && (*argvW)[2]==':') {
2313 opt_t=strtoulW(&(*argvW)[3], NULL, 16);
2314 } else if (tolowerW(c)=='x' || tolowerW(c)=='y') {
2315 /* Ignored for compatibility with Windows */
2318 if ((*argvW)[2]==0) {
2319 argvW++;
2320 args--;
2322 else /* handle `cmd /cnotepad.exe` and `cmd /x/c ...` */
2324 *argvW+=2;
2327 if (opt_c || opt_k) /* break out of parsing immediately after c or k */
2328 break;
2331 if (opt_q) {
2332 static const WCHAR eoff[] = {'O','F','F','\0'};
2333 WCMD_echo(eoff);
2336 if (opt_c || opt_k) {
2337 int len,qcount;
2338 WCHAR** arg;
2339 int argsLeft;
2340 WCHAR* p;
2342 /* opt_s left unflagged if the command starts with and contains exactly
2343 * one quoted string (exactly two quote characters). The quoted string
2344 * must be an executable name that has whitespace and must not have the
2345 * following characters: &<>()@^| */
2347 /* Build the command to execute */
2348 len = 0;
2349 qcount = 0;
2350 argsLeft = args;
2351 for (arg = argvW; argsLeft>0; arg++,argsLeft--)
2353 int has_space,bcount;
2354 WCHAR* a;
2356 has_space=0;
2357 bcount=0;
2358 a=*arg;
2359 if( !*a ) has_space=1;
2360 while (*a!='\0') {
2361 if (*a=='\\') {
2362 bcount++;
2363 } else {
2364 if (*a==' ' || *a=='\t') {
2365 has_space=1;
2366 } else if (*a=='"') {
2367 /* doubling of '\' preceding a '"',
2368 * plus escaping of said '"'
2370 len+=2*bcount+1;
2371 qcount++;
2373 bcount=0;
2375 a++;
2377 len+=(a-*arg) + 1; /* for the separating space */
2378 if (has_space)
2380 len+=2; /* for the quotes */
2381 qcount+=2;
2385 if (qcount!=2)
2386 opt_s=1;
2388 /* check argvW[0] for a space and invalid characters */
2389 if (!opt_s) {
2390 opt_s=1;
2391 p=*argvW;
2392 while (*p!='\0') {
2393 if (*p=='&' || *p=='<' || *p=='>' || *p=='(' || *p==')'
2394 || *p=='@' || *p=='^' || *p=='|') {
2395 opt_s=1;
2396 break;
2398 if (*p==' ')
2399 opt_s=0;
2400 p++;
2404 cmd = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
2405 if (!cmd)
2406 exit(1);
2408 p = cmd;
2409 argsLeft = args;
2410 for (arg = argvW; argsLeft>0; arg++,argsLeft--)
2412 int has_space,has_quote;
2413 WCHAR* a;
2415 /* Check for quotes and spaces in this argument */
2416 has_space=has_quote=0;
2417 a=*arg;
2418 if( !*a ) has_space=1;
2419 while (*a!='\0') {
2420 if (*a==' ' || *a=='\t') {
2421 has_space=1;
2422 if (has_quote)
2423 break;
2424 } else if (*a=='"') {
2425 has_quote=1;
2426 if (has_space)
2427 break;
2429 a++;
2432 /* Now transfer it to the command line */
2433 if (has_space)
2434 *p++='"';
2435 if (has_quote) {
2436 int bcount;
2437 WCHAR* a;
2439 bcount=0;
2440 a=*arg;
2441 while (*a!='\0') {
2442 if (*a=='\\') {
2443 *p++=*a;
2444 bcount++;
2445 } else {
2446 if (*a=='"') {
2447 int i;
2449 /* Double all the '\\' preceding this '"', plus one */
2450 for (i=0;i<=bcount;i++)
2451 *p++='\\';
2452 *p++='"';
2453 } else {
2454 *p++=*a;
2456 bcount=0;
2458 a++;
2460 } else {
2461 strcpyW(p,*arg);
2462 p+=strlenW(*arg);
2464 if (has_space)
2465 *p++='"';
2466 *p++=' ';
2468 if (p > cmd)
2469 p--; /* remove last space */
2470 *p = '\0';
2472 WINE_TRACE("/c command line: '%s'\n", wine_dbgstr_w(cmd));
2474 /* strip first and last quote characters if opt_s; check for invalid
2475 * executable is done later */
2476 if (opt_s && *cmd=='\"')
2477 WCMD_strip_quotes(cmd);
2480 if (opt_c) {
2481 /* If we do a "cmd /c command", we don't want to allocate a new
2482 * console since the command returns immediately. Rather, we use
2483 * the currently allocated input and output handles. This allows
2484 * us to pipe to and read from the command interpreter.
2487 /* Parse the command string, without reading any more input */
2488 WCMD_ReadAndParseLine(cmd, &toExecute, INVALID_HANDLE_VALUE);
2489 WCMD_process_commands(toExecute, FALSE, NULL, NULL);
2490 WCMD_free_commands(toExecute);
2491 toExecute = NULL;
2493 HeapFree(GetProcessHeap(), 0, cmd);
2494 return errorlevel;
2497 SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), ENABLE_LINE_INPUT |
2498 ENABLE_ECHO_INPUT | ENABLE_PROCESSED_INPUT);
2499 SetConsoleTitleW(WCMD_LoadMessage(WCMD_CONSTITLE));
2501 /* Note: cmd.exe /c dir does not get a new color, /k dir does */
2502 if (opt_t) {
2503 if (!(((opt_t & 0xF0) >> 4) == (opt_t & 0x0F))) {
2504 defaultColor = opt_t & 0xFF;
2505 param1[0] = 0x00;
2506 WCMD_color();
2508 } else {
2509 /* Check HKCU\Software\Microsoft\Command Processor
2510 Then HKLM\Software\Microsoft\Command Processor
2511 for defaultcolour value
2512 Note Can be supplied as DWORD or REG_SZ
2513 Note2 When supplied as REG_SZ it's in decimal!!! */
2514 HKEY key;
2515 DWORD type;
2516 DWORD value=0, size=4;
2517 static const WCHAR regKeyW[] = {'S','o','f','t','w','a','r','e','\\',
2518 'M','i','c','r','o','s','o','f','t','\\',
2519 'C','o','m','m','a','n','d',' ','P','r','o','c','e','s','s','o','r','\0'};
2520 static const WCHAR dfltColorW[] = {'D','e','f','a','u','l','t','C','o','l','o','r','\0'};
2522 if (RegOpenKeyExW(HKEY_CURRENT_USER, regKeyW,
2523 0, KEY_READ, &key) == ERROR_SUCCESS) {
2524 WCHAR strvalue[4];
2526 /* See if DWORD or REG_SZ */
2527 if (RegQueryValueExW(key, dfltColorW, NULL, &type,
2528 NULL, NULL) == ERROR_SUCCESS) {
2529 if (type == REG_DWORD) {
2530 size = sizeof(DWORD);
2531 RegQueryValueExW(key, dfltColorW, NULL, NULL,
2532 (LPBYTE)&value, &size);
2533 } else if (type == REG_SZ) {
2534 size = sizeof(strvalue)/sizeof(WCHAR);
2535 RegQueryValueExW(key, dfltColorW, NULL, NULL,
2536 (LPBYTE)strvalue, &size);
2537 value = strtoulW(strvalue, NULL, 10);
2540 RegCloseKey(key);
2543 if (value == 0 && RegOpenKeyExW(HKEY_LOCAL_MACHINE, regKeyW,
2544 0, KEY_READ, &key) == ERROR_SUCCESS) {
2545 WCHAR strvalue[4];
2547 /* See if DWORD or REG_SZ */
2548 if (RegQueryValueExW(key, dfltColorW, NULL, &type,
2549 NULL, NULL) == ERROR_SUCCESS) {
2550 if (type == REG_DWORD) {
2551 size = sizeof(DWORD);
2552 RegQueryValueExW(key, dfltColorW, NULL, NULL,
2553 (LPBYTE)&value, &size);
2554 } else if (type == REG_SZ) {
2555 size = sizeof(strvalue)/sizeof(WCHAR);
2556 RegQueryValueExW(key, dfltColorW, NULL, NULL,
2557 (LPBYTE)strvalue, &size);
2558 value = strtoulW(strvalue, NULL, 10);
2561 RegCloseKey(key);
2564 /* If one found, set the screen to that colour */
2565 if (!(((value & 0xF0) >> 4) == (value & 0x0F))) {
2566 defaultColor = value & 0xFF;
2567 param1[0] = 0x00;
2568 WCMD_color();
2573 /* Save cwd into appropriate env var */
2574 GetCurrentDirectoryW(1024, string);
2575 if (IsCharAlphaW(string[0]) && string[1] == ':') {
2576 static const WCHAR fmt[] = {'=','%','c',':','\0'};
2577 wsprintfW(envvar, fmt, string[0]);
2578 SetEnvironmentVariableW(envvar, string);
2579 WINE_TRACE("Set %s to %s\n", wine_dbgstr_w(envvar), wine_dbgstr_w(string));
2582 if (opt_k) {
2583 /* Parse the command string, without reading any more input */
2584 WCMD_ReadAndParseLine(cmd, &toExecute, INVALID_HANDLE_VALUE);
2585 WCMD_process_commands(toExecute, FALSE, NULL, NULL);
2586 WCMD_free_commands(toExecute);
2587 toExecute = NULL;
2588 HeapFree(GetProcessHeap(), 0, cmd);
2592 * Loop forever getting commands and executing them.
2595 SetEnvironmentVariableW(promptW, defaultpromptW);
2596 WCMD_version ();
2597 while (TRUE) {
2599 /* Read until EOF (which for std input is never, but if redirect
2600 in place, may occur */
2601 if (echo_mode) WCMD_show_prompt();
2602 if (!WCMD_ReadAndParseLine(NULL, &toExecute, GetStdHandle(STD_INPUT_HANDLE)))
2603 break;
2604 WCMD_process_commands(toExecute, FALSE, NULL, NULL);
2605 WCMD_free_commands(toExecute);
2606 toExecute = NULL;
2608 return 0;