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
24 * - Cannot handle parameters in quotes
25 * - Lots of functionality missing from builtins
31 #include "wine/debug.h"
33 WINE_DEFAULT_DEBUG_CHANNEL(cmd
);
35 extern const WCHAR inbuilt
[][10];
36 extern struct env_stack
*pushd_directories
;
38 BATCH_CONTEXT
*context
= NULL
;
40 WCHAR quals
[MAXSTRING
], param1
[MAXSTRING
], param2
[MAXSTRING
];
42 FOR_CONTEXT forloopcontext
; /* The 'for' loop context */
43 BOOL delayedsubst
= FALSE
; /* The current delayed substitution setting */
46 BOOL echo_mode
= TRUE
;
48 WCHAR anykey
[100], version_string
[100];
50 static BOOL opt_c
, opt_k
, opt_s
, unicodeOutput
= FALSE
;
52 /* Variables pertaining to paging */
53 static BOOL paged_mode
;
54 static const WCHAR
*pagedMessage
= NULL
;
55 static int line_count
;
56 static int max_height
;
60 #define MAX_WRITECONSOLE_SIZE 65535
63 * Returns a buffer for reading from/writing to file
66 static char *get_file_buffer(void)
68 static char *output_bufA
= NULL
;
70 output_bufA
= heap_xalloc(MAX_WRITECONSOLE_SIZE
);
74 /*******************************************************************
75 * WCMD_output_asis_len - send output to current standard output
77 * Output a formatted unicode string. Ideally this will go to the console
78 * and hence required WriteConsoleW to output it, however if file i/o is
79 * redirected, it needs to be WriteFile'd using OEM (not ANSI) format
81 static void WCMD_output_asis_len(const WCHAR
*message
, DWORD len
, HANDLE device
)
86 /* If nothing to write, return (MORE does this sometimes) */
89 /* Try to write as unicode assuming it is to a console */
90 res
= WriteConsoleW(device
, message
, len
, &nOut
, NULL
);
92 /* If writing to console fails, assume it's file
93 i/o so convert to OEM codepage and output */
95 BOOL usedDefaultChar
= FALSE
;
101 if (!(buffer
= get_file_buffer()))
104 /* Convert to OEM, then output */
105 convertedChars
= WideCharToMultiByte(GetConsoleOutputCP(), 0, message
,
106 len
, buffer
, MAX_WRITECONSOLE_SIZE
,
107 "?", &usedDefaultChar
);
108 WriteFile(device
, buffer
, convertedChars
,
111 WriteFile(device
, message
, len
*sizeof(WCHAR
),
118 /*******************************************************************
119 * WCMD_output - send output to current standard output device.
123 void WINAPIV
WCMD_output (const WCHAR
*format
, ...) {
129 __ms_va_start(ap
,format
);
131 len
= FormatMessageW(FORMAT_MESSAGE_FROM_STRING
|FORMAT_MESSAGE_ALLOCATE_BUFFER
,
132 format
, 0, 0, (LPWSTR
)&string
, 0, &ap
);
134 if (len
== 0 && GetLastError() != ERROR_NO_WORK_DONE
)
135 WINE_FIXME("Could not format string: le=%u, fmt=%s\n", GetLastError(), wine_dbgstr_w(format
));
138 WCMD_output_asis_len(string
, len
, GetStdHandle(STD_OUTPUT_HANDLE
));
143 /*******************************************************************
144 * WCMD_output_stderr - send output to current standard error device.
148 void WINAPIV
WCMD_output_stderr (const WCHAR
*format
, ...) {
154 __ms_va_start(ap
,format
);
156 len
= FormatMessageW(FORMAT_MESSAGE_FROM_STRING
|FORMAT_MESSAGE_ALLOCATE_BUFFER
,
157 format
, 0, 0, (LPWSTR
)&string
, 0, &ap
);
159 if (len
== 0 && GetLastError() != ERROR_NO_WORK_DONE
)
160 WINE_FIXME("Could not format string: le=%u, fmt=%s\n", GetLastError(), wine_dbgstr_w(format
));
163 WCMD_output_asis_len(string
, len
, GetStdHandle(STD_ERROR_HANDLE
));
168 /*******************************************************************
169 * WCMD_format_string - allocate a buffer and format a string
173 WCHAR
* WINAPIV
WCMD_format_string (const WCHAR
*format
, ...)
179 __ms_va_start(ap
,format
);
180 len
= FormatMessageW(FORMAT_MESSAGE_FROM_STRING
|FORMAT_MESSAGE_ALLOCATE_BUFFER
,
181 format
, 0, 0, (LPWSTR
)&string
, 0, &ap
);
183 if (len
== 0 && GetLastError() != ERROR_NO_WORK_DONE
) {
184 WINE_FIXME("Could not format string: le=%u, fmt=%s\n", GetLastError(), wine_dbgstr_w(format
));
185 string
= (WCHAR
*)LocalAlloc(LMEM_FIXED
, 2);
191 void WCMD_enter_paged_mode(const WCHAR
*msg
)
193 CONSOLE_SCREEN_BUFFER_INFO consoleInfo
;
195 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE
), &consoleInfo
)) {
196 max_height
= consoleInfo
.dwSize
.Y
;
197 max_width
= consoleInfo
.dwSize
.X
;
205 pagedMessage
= (msg
==NULL
)? anykey
: msg
;
208 void WCMD_leave_paged_mode(void)
214 /***************************************************************************
217 * Read characters in from a console/file, returning result in Unicode
219 BOOL
WCMD_ReadFile(const HANDLE hIn
, WCHAR
*intoBuf
, const DWORD maxChars
, LPDWORD charsRead
)
224 /* Try to read from console as Unicode */
225 if (ReadConsoleW(hIn
, intoBuf
, maxChars
, charsRead
, NULL
)) return TRUE
;
227 /* We assume it's a file handle and read then convert from assumed OEM codepage */
228 if (!(buffer
= get_file_buffer()))
231 if (!ReadFile(hIn
, buffer
, maxChars
, &numRead
, NULL
))
234 *charsRead
= MultiByteToWideChar(GetConsoleCP(), 0, buffer
, numRead
, intoBuf
, maxChars
);
239 /*******************************************************************
240 * WCMD_output_asis_handle
242 * Send output to specified handle without formatting e.g. when message contains '%'
244 static void WCMD_output_asis_handle (DWORD std_handle
, const WCHAR
*message
) {
248 HANDLE handle
= GetStdHandle(std_handle
);
253 while (*ptr
&& *ptr
!='\n' && (numChars
< max_width
)) {
257 if (*ptr
== '\n') ptr
++;
258 WCMD_output_asis_len(message
, ptr
- message
, handle
);
260 if (++line_count
>= max_height
- 1) {
262 WCMD_output_asis_len(pagedMessage
, lstrlenW(pagedMessage
), handle
);
263 WCMD_ReadFile(GetStdHandle(STD_INPUT_HANDLE
), string
, ARRAY_SIZE(string
), &count
);
265 } while (((message
= ptr
) != NULL
) && (*ptr
));
267 WCMD_output_asis_len(message
, lstrlenW(message
), handle
);
271 /*******************************************************************
274 * Send output to current standard output device, without formatting
275 * e.g. when message contains '%'
277 void WCMD_output_asis (const WCHAR
*message
) {
278 WCMD_output_asis_handle(STD_OUTPUT_HANDLE
, message
);
281 /*******************************************************************
282 * WCMD_output_asis_stderr
284 * Send output to current standard error device, without formatting
285 * e.g. when message contains '%'
287 void WCMD_output_asis_stderr (const WCHAR
*message
) {
288 WCMD_output_asis_handle(STD_ERROR_HANDLE
, message
);
291 /****************************************************************************
294 * Print the message for GetLastError
297 void WCMD_print_error (void) {
302 error_code
= GetLastError ();
303 status
= FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
,
304 NULL
, error_code
, 0, (LPWSTR
) &lpMsgBuf
, 0, NULL
);
306 WINE_FIXME ("Cannot display message for error %d, status %d\n",
307 error_code
, GetLastError());
311 WCMD_output_asis_len(lpMsgBuf
, lstrlenW(lpMsgBuf
),
312 GetStdHandle(STD_ERROR_HANDLE
));
313 LocalFree (lpMsgBuf
);
314 WCMD_output_asis_len(L
"\r\n", lstrlenW(L
"\r\n"), GetStdHandle(STD_ERROR_HANDLE
));
318 /******************************************************************************
321 * Display the prompt on STDout
325 static void WCMD_show_prompt (BOOL newLine
) {
328 WCHAR out_string
[MAX_PATH
], curdir
[MAX_PATH
], prompt_string
[MAX_PATH
];
332 len
= GetEnvironmentVariableW(L
"PROMPT", prompt_string
, ARRAY_SIZE(prompt_string
));
333 if ((len
== 0) || (len
>= ARRAY_SIZE(prompt_string
))) {
334 lstrcpyW(prompt_string
, L
"$P$G");
350 switch (toupper(*p
)) {
364 GetDateFormatW(LOCALE_USER_DEFAULT
, DATE_SHORTDATE
, NULL
, NULL
, q
, MAX_PATH
- (q
- out_string
));
383 status
= GetCurrentDirectoryW(ARRAY_SIZE(curdir
), curdir
);
389 status
= GetCurrentDirectoryW(ARRAY_SIZE(curdir
), curdir
);
391 lstrcatW (q
, curdir
);
402 GetTimeFormatW(LOCALE_USER_DEFAULT
, 0, NULL
, NULL
, q
, MAX_PATH
);
406 lstrcatW (q
, version_string
);
413 if (pushd_directories
) {
414 memset(q
, '+', pushd_directories
->u
.stackdepth
);
415 q
= q
+ pushd_directories
->u
.stackdepth
;
423 WCMD_output_asis (out_string
);
426 void *heap_xalloc(size_t size
)
430 ret
= heap_alloc(size
);
432 ERR("Out of memory\n");
439 /*************************************************************************
441 * Replaces a portion of a Unicode string with the specified string.
442 * It's up to the caller to ensure there is enough space in the
443 * destination buffer.
445 void WCMD_strsubstW(WCHAR
*start
, const WCHAR
*next
, const WCHAR
*insert
, int len
) {
448 len
=insert
? lstrlenW(insert
) : 0;
449 if (start
+len
!= next
)
450 memmove(start
+len
, next
, (lstrlenW(next
) + 1) * sizeof(*next
));
452 memcpy(start
, insert
, len
* sizeof(*insert
));
455 /***************************************************************************
456 * WCMD_skip_leading_spaces
458 * Return a pointer to the first non-whitespace character of string.
459 * Does not modify the input string.
461 WCHAR
*WCMD_skip_leading_spaces (WCHAR
*string
) {
466 while (*ptr
== ' ' || *ptr
== '\t') ptr
++;
470 /***************************************************************************
471 * WCMD_keyword_ws_found
473 * Checks if the string located at ptr matches a keyword (of length len)
474 * followed by a whitespace character (space or tab)
476 BOOL
WCMD_keyword_ws_found(const WCHAR
*keyword
, const WCHAR
*ptr
) {
477 const int len
= lstrlenW(keyword
);
478 return (CompareStringW(LOCALE_USER_DEFAULT
, NORM_IGNORECASE
| SORT_STRINGSORT
,
479 ptr
, len
, keyword
, len
) == CSTR_EQUAL
)
480 && ((*(ptr
+ len
) == ' ') || (*(ptr
+ len
) == '\t'));
483 /*************************************************************************
486 * Remove first and last quote WCHARacters, preserving all other text
487 * Returns the location of the final quote
489 WCHAR
*WCMD_strip_quotes(WCHAR
*cmd
) {
490 WCHAR
*src
= cmd
+ 1, *dest
= cmd
, *lastq
= NULL
, *lastquote
;
491 while((*dest
=*src
) != '\0') {
499 while ((*dest
++=*lastq
++) != 0)
506 /*************************************************************************
507 * WCMD_is_magic_envvar
508 * Return TRUE if s is '%'magicvar'%'
509 * and is not masked by a real environment variable.
512 static inline BOOL
WCMD_is_magic_envvar(const WCHAR
*s
, const WCHAR
*magicvar
)
517 return FALSE
; /* Didn't begin with % */
519 if (len
< 2 || s
[len
-1] != '%')
520 return FALSE
; /* Didn't end with another % */
522 if (CompareStringW(LOCALE_USER_DEFAULT
,
523 NORM_IGNORECASE
| SORT_STRINGSORT
,
524 s
+1, len
-2, magicvar
, -1) != CSTR_EQUAL
) {
525 /* Name doesn't match. */
529 if (GetEnvironmentVariableW(magicvar
, NULL
, 0) > 0) {
530 /* Masked by real environment variable. */
537 /*************************************************************************
540 * Expands environment variables, allowing for WCHARacter substitution
542 static WCHAR
*WCMD_expand_envvar(WCHAR
*start
, WCHAR startchar
)
544 WCHAR
*endOfVar
= NULL
, *s
;
545 WCHAR
*colonpos
= NULL
;
546 WCHAR thisVar
[MAXSTRING
];
547 WCHAR thisVarContents
[MAXSTRING
];
548 WCHAR savedchar
= 0x00;
550 WCHAR Delims
[] = L
"%:"; /* First char gets replaced appropriately */
552 WINE_TRACE("Expanding: %s (%c)\n", wine_dbgstr_w(start
), startchar
);
554 /* Find the end of the environment variable, and extract name */
555 Delims
[0] = startchar
;
556 endOfVar
= wcspbrk(start
+1, Delims
);
558 if (endOfVar
== NULL
|| *endOfVar
==' ') {
560 /* In batch program, missing terminator for % and no following
561 ':' just removes the '%' */
563 WCMD_strsubstW(start
, start
+ 1, NULL
, 0);
567 /* In command processing, just ignore it - allows command line
568 syntax like: for %i in (a.a) do echo %i */
573 /* If ':' found, process remaining up until '%' (or stop at ':' if
575 if (*endOfVar
==':') {
576 WCHAR
*endOfVar2
= wcschr(endOfVar
+1, startchar
);
577 if (endOfVar2
!= NULL
) endOfVar
= endOfVar2
;
580 memcpy(thisVar
, start
, ((endOfVar
- start
) + 1) * sizeof(WCHAR
));
581 thisVar
[(endOfVar
- start
)+1] = 0x00;
582 colonpos
= wcschr(thisVar
+1, ':');
584 /* If there's complex substitution, just need %var% for now
585 to get the expanded data to play with */
587 *colonpos
= startchar
;
588 savedchar
= *(colonpos
+1);
589 *(colonpos
+1) = 0x00;
592 /* By now, we know the variable we want to expand but it may be
593 surrounded by '!' if we are in delayed expansion - if so convert
595 if (startchar
=='!') {
597 thisVar
[(endOfVar
- start
)] = '%';
599 WINE_TRACE("Retrieving contents of %s\n", wine_dbgstr_w(thisVar
));
601 /* Expand to contents, if unchanged, return */
602 /* Handle DATE, TIME, ERRORLEVEL and CD replacements allowing */
603 /* override if existing env var called that name */
604 if (WCMD_is_magic_envvar(thisVar
, L
"ERRORLEVEL")) {
605 wsprintfW(thisVarContents
, L
"%d", errorlevel
);
606 len
= lstrlenW(thisVarContents
);
607 } else if (WCMD_is_magic_envvar(thisVar
, L
"DATE")) {
608 GetDateFormatW(LOCALE_USER_DEFAULT
, DATE_SHORTDATE
, NULL
,
609 NULL
, thisVarContents
, MAXSTRING
);
610 len
= lstrlenW(thisVarContents
);
611 } else if (WCMD_is_magic_envvar(thisVar
, L
"TIME")) {
612 GetTimeFormatW(LOCALE_USER_DEFAULT
, TIME_NOSECONDS
, NULL
,
613 NULL
, thisVarContents
, MAXSTRING
);
614 len
= lstrlenW(thisVarContents
);
615 } else if (WCMD_is_magic_envvar(thisVar
, L
"CD")) {
616 GetCurrentDirectoryW(MAXSTRING
, thisVarContents
);
617 len
= lstrlenW(thisVarContents
);
618 } else if (WCMD_is_magic_envvar(thisVar
, L
"RANDOM")) {
619 wsprintfW(thisVarContents
, L
"%d", rand() % 32768);
620 len
= lstrlenW(thisVarContents
);
623 len
= ExpandEnvironmentStringsW(thisVar
, thisVarContents
, ARRAY_SIZE(thisVarContents
));
629 /* In a batch program, unknown env vars are replaced with nothing,
630 note syntax %garbage:1,3% results in anything after the ':'
632 From the command line, you just get back what you entered */
633 if (lstrcmpiW(thisVar
, thisVarContents
) == 0) {
635 /* Restore the complex part after the compare */
638 *(colonpos
+1) = savedchar
;
641 /* Command line - just ignore this */
642 if (context
== NULL
) return endOfVar
+1;
645 /* Batch - replace unknown env var with nothing */
646 if (colonpos
== NULL
) {
647 WCMD_strsubstW(start
, endOfVar
+ 1, NULL
, 0);
649 len
= lstrlenW(thisVar
);
650 thisVar
[len
-1] = 0x00;
651 /* If %:...% supplied, : is retained */
652 if (colonpos
== thisVar
+1) {
653 WCMD_strsubstW(start
, endOfVar
+ 1, colonpos
, -1);
655 WCMD_strsubstW(start
, endOfVar
+ 1, colonpos
+ 1, -1);
662 /* See if we need to do complex substitution (any ':'s), if not
663 then our work here is done */
664 if (colonpos
== NULL
) {
665 WCMD_strsubstW(start
, endOfVar
+ 1, thisVarContents
, -1);
669 /* Restore complex bit */
671 *(colonpos
+1) = savedchar
;
674 Handle complex substitutions:
675 xxx=yyy (replace xxx with yyy)
676 *xxx=yyy (replace up to and including xxx with yyy)
677 ~x (from x WCHARs in)
678 ~-x (from x WCHARs from the end)
679 ~x,y (from x WCHARs in for y WCHARacters)
680 ~x,-y (from x WCHARs in until y WCHARacters from the end)
683 /* ~ is substring manipulation */
684 if (savedchar
== '~') {
686 int substrposition
, substrlength
= 0;
687 WCHAR
*commapos
= wcschr(colonpos
+2, ',');
690 substrposition
= wcstol(colonpos
+2, NULL
, 10);
691 if (commapos
) substrlength
= wcstol(commapos
+1, NULL
, 10);
694 if (substrposition
>= 0) {
695 startCopy
= &thisVarContents
[min(substrposition
, len
)];
697 startCopy
= &thisVarContents
[max(0, len
+substrposition
-1)];
700 if (commapos
== NULL
) {
702 WCMD_strsubstW(start
, endOfVar
+ 1, startCopy
, -1);
703 } else if (substrlength
< 0) {
705 int copybytes
= (len
+substrlength
-1)-(startCopy
-thisVarContents
);
706 if (copybytes
> len
) copybytes
= len
;
707 else if (copybytes
< 0) copybytes
= 0;
708 WCMD_strsubstW(start
, endOfVar
+ 1, startCopy
, copybytes
);
710 substrlength
= min(substrlength
, len
- (startCopy
- thisVarContents
+ 1));
711 WCMD_strsubstW(start
, endOfVar
+ 1, startCopy
, substrlength
);
714 /* search and replace manipulation */
716 WCHAR
*equalspos
= wcsstr(colonpos
, L
"=");
717 WCHAR
*replacewith
= equalspos
+1;
722 if (equalspos
== NULL
) return start
+1;
723 s
= heap_strdupW(endOfVar
+ 1);
725 /* Null terminate both strings */
726 thisVar
[lstrlenW(thisVar
)-1] = 0x00;
729 /* Since we need to be case insensitive, copy the 2 buffers */
730 searchIn
= heap_strdupW(thisVarContents
);
731 CharUpperBuffW(searchIn
, lstrlenW(thisVarContents
));
732 searchFor
= heap_strdupW(colonpos
+1);
733 CharUpperBuffW(searchFor
, lstrlenW(colonpos
+1));
735 /* Handle wildcard case */
736 if (*(colonpos
+1) == '*') {
737 /* Search for string to replace */
738 found
= wcsstr(searchIn
, searchFor
+1);
742 lstrcpyW(start
, replacewith
);
743 lstrcatW(start
, thisVarContents
+ (found
-searchIn
) + lstrlenW(searchFor
+1));
747 lstrcpyW(start
, thisVarContents
);
752 /* Loop replacing all instances */
753 WCHAR
*lastFound
= searchIn
;
754 WCHAR
*outputposn
= start
;
757 while ((found
= wcsstr(lastFound
, searchFor
))) {
758 lstrcpynW(outputposn
,
759 thisVarContents
+ (lastFound
-searchIn
),
760 (found
- lastFound
)+1);
761 outputposn
= outputposn
+ (found
- lastFound
);
762 lstrcatW(outputposn
, replacewith
);
763 outputposn
= outputposn
+ lstrlenW(replacewith
);
764 lastFound
= found
+ lstrlenW(searchFor
);
767 thisVarContents
+ (lastFound
-searchIn
));
768 lstrcatW(outputposn
, s
);
772 heap_free(searchFor
);
777 /*****************************************************************************
778 * Expand the command. Native expands lines from batch programs as they are
779 * read in and not again, except for 'for' variable substitution.
780 * eg. As evidence, "echo %1 && shift && echo %1" or "echo %%path%%"
781 * atExecute is TRUE when the expansion is occurring as the command is executed
782 * rather than at parse time, i.e. delayed expansion and for loops need to be
785 static void handleExpansion(WCHAR
*cmd
, BOOL atExecute
, BOOL delayed
) {
787 /* For commands in a context (batch program): */
788 /* Expand environment variables in a batch file %{0-9} first */
789 /* including support for any ~ modifiers */
791 /* Expand the DATE, TIME, CD, RANDOM and ERRORLEVEL special */
792 /* names allowing environment variable overrides */
793 /* NOTE: To support the %PATH:xxx% syntax, also perform */
794 /* manual expansion of environment variables here */
799 WCHAR
*delayedp
= NULL
;
800 WCHAR startchar
= '%';
803 /* Display the FOR variables in effect */
805 if (forloopcontext
.variable
[i
]) {
806 WINE_TRACE("FOR variable context: %c = '%s'\n",
807 i
<26?i
+'a':(i
-26)+'A',
808 wine_dbgstr_w(forloopcontext
.variable
[i
]));
812 /* Find the next environment variable delimiter */
813 normalp
= wcschr(p
, '%');
814 if (delayed
) delayedp
= wcschr(p
, '!');
815 if (!normalp
) p
= delayedp
;
816 else if (!delayedp
) p
= normalp
;
817 else p
= min(p
,delayedp
);
818 if (p
) startchar
= *p
;
822 WINE_TRACE("Translate command:%s %d (at: %s)\n",
823 wine_dbgstr_w(cmd
), atExecute
, wine_dbgstr_w(p
));
826 /* Don't touch %% unless it's in Batch */
827 if (!atExecute
&& *(p
+1) == startchar
) {
829 WCMD_strsubstW(p
, p
+1, NULL
, 0);
833 /* Replace %~ modifications if in batch program */
834 } else if (*(p
+1) == '~') {
835 WCMD_HandleTildeModifiers(&p
, atExecute
);
838 /* Replace use of %0...%9 if in batch program*/
839 } else if (!atExecute
&& context
&& (i
>= 0) && (i
<= 9) && startchar
== '%') {
840 t
= WCMD_parameter(context
-> command
, i
+ context
-> shift_count
[i
],
842 WCMD_strsubstW(p
, p
+2, t
, -1);
844 /* Replace use of %* if in batch program*/
845 } else if (!atExecute
&& context
&& *(p
+1)=='*' && startchar
== '%') {
846 WCHAR
*startOfParms
= NULL
;
847 WCHAR
*thisParm
= WCMD_parameter(context
-> command
, 0, &startOfParms
, TRUE
, TRUE
);
848 if (startOfParms
!= NULL
) {
849 startOfParms
+= lstrlenW(thisParm
);
850 while (*startOfParms
==' ' || *startOfParms
== '\t') startOfParms
++;
851 WCMD_strsubstW(p
, p
+2, startOfParms
, -1);
853 WCMD_strsubstW(p
, p
+2, NULL
, 0);
856 int forvaridx
= FOR_VAR_IDX(*(p
+1));
857 if (startchar
== '%' && forvaridx
!= -1 && forloopcontext
.variable
[forvaridx
]) {
858 /* Replace the 2 characters, % and for variable character */
859 WCMD_strsubstW(p
, p
+ 2, forloopcontext
.variable
[forvaridx
], -1);
860 } else if (!atExecute
|| startchar
== '!') {
861 p
= WCMD_expand_envvar(p
, startchar
);
863 /* In a FOR loop, see if this is the variable to replace */
864 } else { /* Ignore %'s on second pass of batch program */
869 /* Find the next environment variable delimiter */
870 normalp
= wcschr(p
, '%');
871 if (delayed
) delayedp
= wcschr(p
, '!');
872 if (!normalp
) p
= delayedp
;
873 else if (!delayedp
) p
= normalp
;
874 else p
= min(p
,delayedp
);
875 if (p
) startchar
= *p
;
882 /*******************************************************************
883 * WCMD_parse - parse a command into parameters and qualifiers.
885 * On exit, all qualifiers are concatenated into q, the first string
886 * not beginning with "/" is in p1 and the
887 * second in p2. Any subsequent non-qualifier strings are lost.
888 * Parameters in quotes are handled.
890 static void WCMD_parse (const WCHAR
*s
, WCHAR
*q
, WCHAR
*p1
, WCHAR
*p2
)
894 *q
= *p1
= *p2
= '\0';
899 while ((*s
!= '\0') && (*s
!= ' ') && *s
!= '/') {
900 *q
++ = towupper (*s
++);
910 while ((*s
!= '\0') && (*s
!= '"')) {
911 if (p
== 0) *p1
++ = *s
++;
912 else if (p
== 1) *p2
++ = *s
++;
915 if (p
== 0) *p1
= '\0';
916 if (p
== 1) *p2
= '\0';
923 while ((*s
!= '\0') && (*s
!= ' ') && (*s
!= '\t')
924 && (*s
!= '=') && (*s
!= ',') ) {
925 if (p
== 0) *p1
++ = *s
++;
926 else if (p
== 1) *p2
++ = *s
++;
929 /* Skip concurrent parms */
930 while ((*s
== ' ') || (*s
== '\t') || (*s
== '=') || (*s
== ',') ) s
++;
932 if (p
== 0) *p1
= '\0';
933 if (p
== 1) *p2
= '\0';
939 static void init_msvcrt_io_block(STARTUPINFOW
* st
)
942 /* fetch the parent MSVCRT info block if any, so that the child can use the
943 * same handles as its grand-father
945 st_p
.cb
= sizeof(STARTUPINFOW
);
946 GetStartupInfoW(&st_p
);
947 st
->cbReserved2
= st_p
.cbReserved2
;
948 st
->lpReserved2
= st_p
.lpReserved2
;
949 if (st_p
.cbReserved2
&& st_p
.lpReserved2
)
951 unsigned num
= *(unsigned*)st_p
.lpReserved2
;
957 /* Override the entries for fd 0,1,2 if we happened
958 * to change those std handles (this depends on the way cmd sets
959 * its new input & output handles)
961 sz
= max(sizeof(unsigned) + (sizeof(char) + sizeof(HANDLE
)) * 3, st_p
.cbReserved2
);
962 ptr
= heap_xalloc(sz
);
963 flags
= (char*)(ptr
+ sizeof(unsigned));
964 handles
= (HANDLE
*)(flags
+ num
* sizeof(char));
966 memcpy(ptr
, st_p
.lpReserved2
, st_p
.cbReserved2
);
967 st
->cbReserved2
= sz
;
968 st
->lpReserved2
= ptr
;
970 #define WX_OPEN 0x01 /* see dlls/msvcrt/file.c */
971 if (num
<= 0 || (flags
[0] & WX_OPEN
))
973 handles
[0] = GetStdHandle(STD_INPUT_HANDLE
);
976 if (num
<= 1 || (flags
[1] & WX_OPEN
))
978 handles
[1] = GetStdHandle(STD_OUTPUT_HANDLE
);
981 if (num
<= 2 || (flags
[2] & WX_OPEN
))
983 handles
[2] = GetStdHandle(STD_ERROR_HANDLE
);
990 /******************************************************************************
993 * Execute a command line as an external program. Must allow recursion.
996 * Manual testing under windows shows PATHEXT plays a key part in this,
997 * and the search algorithm and precedence appears to be as follows.
1000 * If directory supplied on command, just use that directory
1001 * If extension supplied on command, look for that explicit name first
1002 * Otherwise, search in each directory on the path
1004 * If extension supplied on command, look for that explicit name first
1005 * Then look for supplied name .* (even if extension supplied, so
1006 * 'garbage.exe' will match 'garbage.exe.cmd')
1007 * If any found, cycle through PATHEXT looking for name.exe one by one
1009 * Once a match has been found, it is launched - Code currently uses
1010 * findexecutable to achieve this which is left untouched.
1011 * If an executable has not been found, and we were launched through
1012 * a call, we need to check if the command is an internal command,
1013 * so go back through wcmd_execute.
1016 void WCMD_run_program (WCHAR
*command
, BOOL called
)
1018 WCHAR temp
[MAX_PATH
];
1019 WCHAR pathtosearch
[MAXSTRING
];
1021 WCHAR stemofsearch
[MAX_PATH
]; /* maximum allowed executable name is
1022 MAX_PATH, including null character */
1024 WCHAR pathext
[MAXSTRING
];
1026 BOOL extensionsupplied
= FALSE
;
1027 BOOL explicit_path
= FALSE
;
1031 /* Quick way to get the filename is to extract the first argument. */
1032 WINE_TRACE("Running '%s' (%d)\n", wine_dbgstr_w(command
), called
);
1033 firstParam
= WCMD_parameter(command
, 0, NULL
, FALSE
, TRUE
);
1034 if (!firstParam
) return;
1036 if (!firstParam
[0]) {
1041 /* Calculate the search path and stem to search for */
1042 if (wcspbrk(firstParam
, L
"/\\:") == NULL
) { /* No explicit path given, search path */
1043 lstrcpyW(pathtosearch
, L
".;");
1044 len
= GetEnvironmentVariableW(L
"PATH", &pathtosearch
[2], ARRAY_SIZE(pathtosearch
)-2);
1045 if ((len
== 0) || (len
>= ARRAY_SIZE(pathtosearch
) - 2)) {
1046 lstrcpyW(pathtosearch
, L
".");
1048 if (wcschr(firstParam
, '.') != NULL
) extensionsupplied
= TRUE
;
1049 if (lstrlenW(firstParam
) >= MAX_PATH
)
1051 WCMD_output_asis_stderr(WCMD_LoadMessage(WCMD_LINETOOLONG
));
1055 lstrcpyW(stemofsearch
, firstParam
);
1059 /* Convert eg. ..\fred to include a directory by removing file part */
1060 GetFullPathNameW(firstParam
, ARRAY_SIZE(pathtosearch
), pathtosearch
, NULL
);
1061 lastSlash
= wcsrchr(pathtosearch
, '\\');
1062 if (lastSlash
&& wcschr(lastSlash
, '.') != NULL
) extensionsupplied
= TRUE
;
1063 lstrcpyW(stemofsearch
, lastSlash
+1);
1065 /* Reduce pathtosearch to a path with trailing '\' to support c:\a.bat and
1066 c:\windows\a.bat syntax */
1067 if (lastSlash
) *(lastSlash
+ 1) = 0x00;
1068 explicit_path
= TRUE
;
1071 /* Now extract PATHEXT */
1072 len
= GetEnvironmentVariableW(L
"PATHEXT", pathext
, ARRAY_SIZE(pathext
));
1073 if ((len
== 0) || (len
>= ARRAY_SIZE(pathext
))) {
1074 lstrcpyW(pathext
, L
".bat;.com;.cmd;.exe");
1077 /* Loop through the search path, dir by dir */
1078 pathposn
= pathtosearch
;
1079 WINE_TRACE("Searching in '%s' for '%s'\n", wine_dbgstr_w(pathtosearch
),
1080 wine_dbgstr_w(stemofsearch
));
1082 WCHAR thisDir
[MAX_PATH
] = {'\0'};
1086 BOOL inside_quotes
= FALSE
;
1090 lstrcpyW(thisDir
, pathposn
);
1095 /* Work on the next directory on the search path */
1097 while ((inside_quotes
|| *pos
!= ';') && *pos
!= 0)
1100 inside_quotes
= !inside_quotes
;
1104 if (*pos
) /* Reached semicolon */
1106 memcpy(thisDir
, pathposn
, (pos
-pathposn
) * sizeof(WCHAR
));
1107 thisDir
[(pos
-pathposn
)] = 0x00;
1110 else /* Reached string end */
1112 lstrcpyW(thisDir
, pathposn
);
1117 length
= lstrlenW(thisDir
);
1118 if (thisDir
[length
- 1] == '"')
1119 thisDir
[length
- 1] = 0;
1121 if (*thisDir
!= '"')
1122 lstrcpyW(temp
, thisDir
);
1124 lstrcpyW(temp
, thisDir
+ 1);
1126 /* Since you can have eg. ..\.. on the path, need to expand
1127 to full information */
1128 GetFullPathNameW(temp
, MAX_PATH
, thisDir
, NULL
);
1131 /* 1. If extension supplied, see if that file exists */
1132 lstrcatW(thisDir
, L
"\\");
1133 lstrcatW(thisDir
, stemofsearch
);
1134 pos
= &thisDir
[lstrlenW(thisDir
)]; /* Pos = end of name */
1136 /* 1. If extension supplied, see if that file exists */
1137 if (extensionsupplied
) {
1138 if (GetFileAttributesW(thisDir
) != INVALID_FILE_ATTRIBUTES
) {
1143 /* 2. Any .* matches? */
1146 WIN32_FIND_DATAW finddata
;
1148 lstrcatW(thisDir
, L
".*");
1149 h
= FindFirstFileW(thisDir
, &finddata
);
1151 if (h
!= INVALID_HANDLE_VALUE
) {
1153 WCHAR
*thisExt
= pathext
;
1155 /* 3. Yes - Try each path ext */
1157 WCHAR
*nextExt
= wcschr(thisExt
, ';');
1160 memcpy(pos
, thisExt
, (nextExt
-thisExt
) * sizeof(WCHAR
));
1161 pos
[(nextExt
-thisExt
)] = 0x00;
1162 thisExt
= nextExt
+1;
1164 lstrcpyW(pos
, thisExt
);
1168 if (GetFileAttributesW(thisDir
) != INVALID_FILE_ATTRIBUTES
) {
1176 /* Once found, launch it */
1179 PROCESS_INFORMATION pe
;
1183 WCHAR
*ext
= wcsrchr( thisDir
, '.' );
1185 WINE_TRACE("Found as %s\n", wine_dbgstr_w(thisDir
));
1187 /* Special case BAT and CMD */
1188 if (ext
&& (!wcsicmp(ext
, L
".bat") || !wcsicmp(ext
, L
".cmd"))) {
1189 BOOL oldinteractive
= interactive
;
1190 interactive
= FALSE
;
1191 WCMD_batch (thisDir
, command
, called
, NULL
, INVALID_HANDLE_VALUE
);
1192 interactive
= oldinteractive
;
1196 /* thisDir contains the file to be launched, but with what?
1197 eg. a.exe will require a.exe to be launched, a.html may be iexplore */
1198 hinst
= FindExecutableW (thisDir
, NULL
, temp
);
1199 if ((INT_PTR
)hinst
< 32)
1202 console
= SHGetFileInfoW(temp
, 0, &psfi
, sizeof(psfi
), SHGFI_EXETYPE
);
1204 ZeroMemory (&st
, sizeof(STARTUPINFOW
));
1205 st
.cb
= sizeof(STARTUPINFOW
);
1206 init_msvcrt_io_block(&st
);
1208 /* Launch the process and if a CUI wait on it to complete
1209 Note: Launching internal wine processes cannot specify a full path to exe */
1210 status
= CreateProcessW(thisDir
,
1211 command
, NULL
, NULL
, TRUE
, 0, NULL
, NULL
, &st
, &pe
);
1212 heap_free(st
.lpReserved2
);
1213 if ((opt_c
|| opt_k
) && !opt_s
&& !status
1214 && GetLastError()==ERROR_FILE_NOT_FOUND
&& command
[0]=='\"') {
1215 /* strip first and last quote WCHARacters and try again */
1216 WCMD_strip_quotes(command
);
1218 WCMD_run_program(command
, called
);
1225 /* Always wait when non-interactive (cmd /c or in batch program),
1226 or for console applications */
1227 if (!interactive
|| (console
&& !HIWORD(console
)))
1228 WaitForSingleObject (pe
.hProcess
, INFINITE
);
1229 GetExitCodeProcess (pe
.hProcess
, &errorlevel
);
1230 if (errorlevel
== STILL_ACTIVE
) errorlevel
= 0;
1232 CloseHandle(pe
.hProcess
);
1233 CloseHandle(pe
.hThread
);
1239 /* Not found anywhere - were we called? */
1241 CMD_LIST
*toExecute
= NULL
; /* Commands left to be executed */
1243 /* Parse the command string, without reading any more input */
1244 WCMD_ReadAndParseLine(command
, &toExecute
, INVALID_HANDLE_VALUE
);
1245 WCMD_process_commands(toExecute
, FALSE
, called
);
1246 WCMD_free_commands(toExecute
);
1251 /* Not found anywhere - give up */
1252 WCMD_output_stderr(WCMD_LoadMessage(WCMD_NO_COMMAND_FOUND
), command
);
1254 /* If a command fails to launch, it sets errorlevel 9009 - which
1255 does not seem to have any associated constant definition */
1261 /*****************************************************************************
1262 * Process one command. If the command is EXIT this routine does not return.
1263 * We will recurse through here executing batch files.
1264 * Note: If call is used to a non-existing program, we reparse the line and
1265 * try to run it as an internal command. 'retrycall' represents whether
1266 * we are attempting this retry.
1268 void WCMD_execute (const WCHAR
*command
, const WCHAR
*redirects
,
1269 CMD_LIST
**cmdList
, BOOL retrycall
)
1271 WCHAR
*cmd
, *parms_start
, *redir
;
1273 int status
, i
, cmd_index
;
1274 DWORD count
, creationDisposition
;
1277 SECURITY_ATTRIBUTES sa
;
1278 WCHAR
*new_cmd
= NULL
;
1279 WCHAR
*new_redir
= NULL
;
1280 HANDLE old_stdhandles
[3] = {GetStdHandle (STD_INPUT_HANDLE
),
1281 GetStdHandle (STD_OUTPUT_HANDLE
),
1282 GetStdHandle (STD_ERROR_HANDLE
)};
1283 DWORD idx_stdhandles
[3] = {STD_INPUT_HANDLE
,
1286 BOOL prev_echo_mode
, piped
= FALSE
;
1288 WINE_TRACE("command on entry:%s (%p)\n",
1289 wine_dbgstr_w(command
), cmdList
);
1291 /* Move copy of the command onto the heap so it can be expanded */
1292 new_cmd
= heap_xalloc(MAXSTRING
* sizeof(WCHAR
));
1293 lstrcpyW(new_cmd
, command
);
1296 /* Move copy of the redirects onto the heap so it can be expanded */
1297 new_redir
= heap_xalloc(MAXSTRING
* sizeof(WCHAR
));
1300 /* Strip leading whitespaces, and a '@' if supplied */
1301 whichcmd
= WCMD_skip_leading_spaces(cmd
);
1302 WINE_TRACE("Command: '%s'\n", wine_dbgstr_w(cmd
));
1303 if (whichcmd
[0] == '@') whichcmd
++;
1305 /* Check if the command entered is internal, and identify which one */
1307 while (IsCharAlphaNumericW(whichcmd
[count
])) {
1310 for (i
=0; i
<=WCMD_EXIT
; i
++) {
1311 if (CompareStringW(LOCALE_USER_DEFAULT
, NORM_IGNORECASE
| SORT_STRINGSORT
,
1312 whichcmd
, count
, inbuilt
[i
], -1) == CSTR_EQUAL
) break;
1315 parms_start
= WCMD_skip_leading_spaces (&whichcmd
[count
]);
1317 /* If the next command is a pipe then we implement pipes by redirecting
1318 the output from this command to a temp file and input into the
1319 next command from that temp file.
1320 Note: Do not do this for a for or if statement as the pipe is for
1321 the individual statements, not the for or if itself.
1322 FIXME: Use of named pipes would make more sense here as currently this
1323 process has to finish before the next one can start but this requires
1324 a change to not wait for the first app to finish but rather the pipe */
1325 if (!(cmd_index
== WCMD_FOR
|| cmd_index
== WCMD_IF
) &&
1326 cmdList
&& (*cmdList
)->nextcommand
&&
1327 (*cmdList
)->nextcommand
->prevDelim
== CMD_PIPE
) {
1329 WCHAR temp_path
[MAX_PATH
];
1331 /* Remember piping is in action */
1332 WINE_TRACE("Output needs to be piped\n");
1335 /* Generate a unique temporary filename */
1336 GetTempPathW(ARRAY_SIZE(temp_path
), temp_path
);
1337 GetTempFileNameW(temp_path
, L
"CMD", 0, (*cmdList
)->nextcommand
->pipeFile
);
1338 WINE_TRACE("Using temporary file of %s\n",
1339 wine_dbgstr_w((*cmdList
)->nextcommand
->pipeFile
));
1342 /* If piped output, send stdout to the pipe by appending >filename to redirects */
1344 wsprintfW (new_redir
, L
"%s > %s", redirects
, (*cmdList
)->nextcommand
->pipeFile
);
1345 WINE_TRACE("Redirects now %s\n", wine_dbgstr_w(new_redir
));
1347 lstrcpyW(new_redir
, redirects
);
1350 /* Expand variables in command line mode only (batch mode will
1351 be expanded as the line is read in, except for 'for' loops) */
1352 handleExpansion(new_cmd
, (context
!= NULL
), delayedsubst
);
1353 handleExpansion(new_redir
, (context
!= NULL
), delayedsubst
);
1356 * Changing default drive has to be handled as a special case, anything
1357 * else if it exists after whitespace is ignored
1360 if ((cmd
[1] == ':') && IsCharAlphaW(cmd
[0]) &&
1361 (!cmd
[2] || cmd
[2] == ' ' || cmd
[2] == '\t')) {
1363 WCHAR dir
[MAX_PATH
];
1365 /* Ignore potential garbage on the same line */
1368 /* According to MSDN CreateProcess docs, special env vars record
1369 the current directory on each drive, in the form =C:
1370 so see if one specified, and if so go back to it */
1371 lstrcpyW(envvar
, L
"=");
1372 lstrcatW(envvar
, cmd
);
1373 if (GetEnvironmentVariableW(envvar
, dir
, MAX_PATH
) == 0) {
1374 wsprintfW(cmd
, L
"%s\\", cmd
);
1375 WINE_TRACE("No special directory settings, using dir of %s\n", wine_dbgstr_w(cmd
));
1377 WINE_TRACE("Got directory %s as %s\n", wine_dbgstr_w(envvar
), wine_dbgstr_w(cmd
));
1378 status
= SetCurrentDirectoryW(cmd
);
1379 if (!status
) WCMD_print_error ();
1381 heap_free(new_redir
);
1385 sa
.nLength
= sizeof(sa
);
1386 sa
.lpSecurityDescriptor
= NULL
;
1387 sa
.bInheritHandle
= TRUE
;
1390 * Redirect stdin, stdout and/or stderr if required.
1391 * Note: Do not do this for a for or if statement as the pipe is for
1392 * the individual statements, not the for or if itself.
1394 if (!(cmd_index
== WCMD_FOR
|| cmd_index
== WCMD_IF
)) {
1395 /* STDIN could come from a preceding pipe, so delete on close if it does */
1396 if (cmdList
&& (*cmdList
)->pipeFile
[0] != 0x00) {
1397 WINE_TRACE("Input coming from %s\n", wine_dbgstr_w((*cmdList
)->pipeFile
));
1398 h
= CreateFileW((*cmdList
)->pipeFile
, GENERIC_READ
,
1399 FILE_SHARE_READ
| FILE_SHARE_WRITE
, &sa
, OPEN_EXISTING
,
1400 FILE_ATTRIBUTE_NORMAL
| FILE_FLAG_DELETE_ON_CLOSE
, NULL
);
1401 if (h
== INVALID_HANDLE_VALUE
) {
1402 WCMD_print_error ();
1404 heap_free(new_redir
);
1407 SetStdHandle (STD_INPUT_HANDLE
, h
);
1409 /* No need to remember the temporary name any longer once opened */
1410 (*cmdList
)->pipeFile
[0] = 0x00;
1412 /* Otherwise STDIN could come from a '<' redirect */
1413 } else if ((pos
= wcschr(new_redir
,'<')) != NULL
) {
1414 h
= CreateFileW(WCMD_parameter(++pos
, 0, NULL
, FALSE
, FALSE
), GENERIC_READ
, FILE_SHARE_READ
,
1415 &sa
, OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, NULL
);
1416 if (h
== INVALID_HANDLE_VALUE
) {
1417 WCMD_print_error ();
1419 heap_free(new_redir
);
1422 SetStdHandle (STD_INPUT_HANDLE
, h
);
1425 /* Scan the whole command looking for > and 2> */
1426 while (redir
!= NULL
&& ((pos
= wcschr(redir
,'>')) != NULL
)) {
1429 if (pos
> redir
&& (*(pos
-1)=='2'))
1436 creationDisposition
= OPEN_ALWAYS
;
1440 creationDisposition
= CREATE_ALWAYS
;
1443 /* Add support for 2>&1 */
1446 int idx
= *(pos
+1) - '0';
1448 if (DuplicateHandle(GetCurrentProcess(),
1449 GetStdHandle(idx_stdhandles
[idx
]),
1450 GetCurrentProcess(),
1452 0, TRUE
, DUPLICATE_SAME_ACCESS
) == 0) {
1453 WINE_FIXME("Duplicating handle failed with gle %d\n", GetLastError());
1455 WINE_TRACE("Redirect %d (%p) to %d (%p)\n", handle
, GetStdHandle(idx_stdhandles
[idx
]), idx
, h
);
1458 WCHAR
*param
= WCMD_parameter(pos
, 0, NULL
, FALSE
, FALSE
);
1459 h
= CreateFileW(param
, GENERIC_WRITE
, FILE_SHARE_READ
| FILE_SHARE_DELETE
,
1460 &sa
, creationDisposition
, FILE_ATTRIBUTE_NORMAL
, NULL
);
1461 if (h
== INVALID_HANDLE_VALUE
) {
1462 WCMD_print_error ();
1464 heap_free(new_redir
);
1467 if (SetFilePointer (h
, 0, NULL
, FILE_END
) ==
1468 INVALID_SET_FILE_POINTER
) {
1469 WCMD_print_error ();
1471 WINE_TRACE("Redirect %d to '%s' (%p)\n", handle
, wine_dbgstr_w(param
), h
);
1474 SetStdHandle (idx_stdhandles
[handle
], h
);
1477 WINE_TRACE("Not touching redirects for a FOR or IF command\n");
1479 WCMD_parse (parms_start
, quals
, param1
, param2
);
1480 WINE_TRACE("param1: %s, param2: %s\n", wine_dbgstr_w(param1
), wine_dbgstr_w(param2
));
1482 if (i
<= WCMD_EXIT
&& (parms_start
[0] == '/') && (parms_start
[1] == '?')) {
1483 /* this is a help request for a builtin program */
1485 memcpy(parms_start
, whichcmd
, count
* sizeof(WCHAR
));
1486 parms_start
[count
] = '\0';
1493 WCMD_call (parms_start
);
1497 WCMD_setshow_default (parms_start
);
1500 WCMD_clear_screen ();
1503 WCMD_copy (parms_start
);
1509 WCMD_setshow_date ();
1513 WCMD_delete (parms_start
);
1516 WCMD_directory (parms_start
);
1519 WCMD_echo(&whichcmd
[count
]);
1522 WCMD_goto (cmdList
);
1525 WCMD_give_help (parms_start
);
1528 WCMD_volume (TRUE
, parms_start
);
1532 WCMD_create_dir (parms_start
);
1538 WCMD_setshow_path (parms_start
);
1544 WCMD_setshow_prompt ();
1554 WCMD_remove_dir (parms_start
);
1557 WCMD_setlocal(parms_start
);
1563 WCMD_setshow_env (parms_start
);
1566 WCMD_shift (parms_start
);
1569 WCMD_start (parms_start
);
1572 WCMD_setshow_time ();
1575 if (lstrlenW(&whichcmd
[count
]) > 0)
1576 WCMD_title(&whichcmd
[count
+1]);
1579 WCMD_type (parms_start
);
1582 WCMD_output_asis(L
"\r\n");
1586 WCMD_verify (parms_start
);
1589 WCMD_volume (FALSE
, parms_start
);
1592 WCMD_pushd(parms_start
);
1598 WCMD_assoc(parms_start
, TRUE
);
1604 WCMD_assoc(parms_start
, FALSE
);
1607 WCMD_more(parms_start
);
1610 WCMD_choice(parms_start
);
1613 WCMD_mklink(parms_start
);
1616 WCMD_exit (cmdList
);
1620 /* Very oddly, probably because of all the special parsing required for
1621 these two commands, neither 'for' nor 'if' is supported when called,
1622 i.e. 'call if 1==1...' will fail. */
1624 if (i
==WCMD_FOR
) WCMD_for (parms_start
, cmdList
);
1625 else if (i
==WCMD_IF
) WCMD_if (parms_start
, cmdList
);
1628 /* else: drop through */
1630 prev_echo_mode
= echo_mode
;
1631 WCMD_run_program (whichcmd
, FALSE
);
1632 echo_mode
= prev_echo_mode
;
1635 heap_free(new_redir
);
1637 /* Restore old handles */
1638 for (i
=0; i
<3; i
++) {
1639 if (old_stdhandles
[i
] != GetStdHandle(idx_stdhandles
[i
])) {
1640 CloseHandle (GetStdHandle (idx_stdhandles
[i
]));
1641 SetStdHandle (idx_stdhandles
[i
], old_stdhandles
[i
]);
1646 /*************************************************************************
1648 * Load a string from the resource file, handling any error
1649 * Returns string retrieved from resource file
1651 WCHAR
*WCMD_LoadMessage(UINT id
) {
1652 static WCHAR msg
[2048];
1654 if (!LoadStringW(GetModuleHandleW(NULL
), id
, msg
, ARRAY_SIZE(msg
))) {
1655 WINE_FIXME("LoadString failed with %d\n", GetLastError());
1656 lstrcpyW(msg
, L
"Failed!");
1661 /***************************************************************************
1664 * Dumps out the parsed command line to ensure syntax is correct
1666 static void WCMD_DumpCommands(CMD_LIST
*commands
) {
1667 CMD_LIST
*thisCmd
= commands
;
1669 WINE_TRACE("Parsed line:\n");
1670 while (thisCmd
!= NULL
) {
1671 WINE_TRACE("%p %d %2.2d %p %s Redir:%s\n",
1674 thisCmd
->bracketDepth
,
1675 thisCmd
->nextcommand
,
1676 wine_dbgstr_w(thisCmd
->command
),
1677 wine_dbgstr_w(thisCmd
->redirects
));
1678 thisCmd
= thisCmd
->nextcommand
;
1682 /***************************************************************************
1685 * Adds a command to the current command list
1687 static void WCMD_addCommand(WCHAR
*command
, int *commandLen
,
1688 WCHAR
*redirs
, int *redirLen
,
1689 WCHAR
**copyTo
, int **copyToLen
,
1690 CMD_DELIMITERS prevDelim
, int curDepth
,
1691 CMD_LIST
**lastEntry
, CMD_LIST
**output
) {
1693 CMD_LIST
*thisEntry
= NULL
;
1695 /* Allocate storage for command */
1696 thisEntry
= heap_xalloc(sizeof(CMD_LIST
));
1698 /* Copy in the command */
1700 thisEntry
->command
= heap_xalloc((*commandLen
+1) * sizeof(WCHAR
));
1701 memcpy(thisEntry
->command
, command
, *commandLen
* sizeof(WCHAR
));
1702 thisEntry
->command
[*commandLen
] = 0x00;
1704 /* Copy in the redirects */
1705 thisEntry
->redirects
= heap_xalloc((*redirLen
+1) * sizeof(WCHAR
));
1706 memcpy(thisEntry
->redirects
, redirs
, *redirLen
* sizeof(WCHAR
));
1707 thisEntry
->redirects
[*redirLen
] = 0x00;
1708 thisEntry
->pipeFile
[0] = 0x00;
1710 /* Reset the lengths */
1713 *copyToLen
= commandLen
;
1717 thisEntry
->command
= NULL
;
1718 thisEntry
->redirects
= NULL
;
1719 thisEntry
->pipeFile
[0] = 0x00;
1722 /* Fill in other fields */
1723 thisEntry
->nextcommand
= NULL
;
1724 thisEntry
->prevDelim
= prevDelim
;
1725 thisEntry
->bracketDepth
= curDepth
;
1727 (*lastEntry
)->nextcommand
= thisEntry
;
1729 *output
= thisEntry
;
1731 *lastEntry
= thisEntry
;
1735 /***************************************************************************
1738 * Checks if the quote pointed to is the end-quote.
1742 * 1) The current parameter ends at EOL or at the beginning
1743 * of a redirection or pipe and not in a quote section.
1745 * 2) If the next character is a space and not in a quote section.
1747 * Returns TRUE if this is an end quote, and FALSE if it is not.
1750 static BOOL
WCMD_IsEndQuote(const WCHAR
*quote
, int quoteIndex
)
1752 int quoteCount
= quoteIndex
;
1755 /* If we are not in a quoted section, then we are not an end-quote */
1761 /* Check how many quotes are left for this parameter */
1762 for(i
=0;quote
[i
];i
++)
1769 /* Quote counting ends at EOL, redirection, space or pipe if current quote is complete */
1770 else if(((quoteCount
% 2) == 0)
1771 && ((quote
[i
] == '<') || (quote
[i
] == '>') || (quote
[i
] == '|') || (quote
[i
] == ' ') ||
1778 /* If the quote is part of the last part of a series of quotes-on-quotes, then it must
1780 if(quoteIndex
>= (quoteCount
/ 2))
1789 /***************************************************************************
1790 * WCMD_ReadAndParseLine
1792 * Either uses supplied input or
1793 * Reads a file from the handle, and then...
1794 * Parse the text buffer, splitting into separate commands
1795 * - unquoted && strings split 2 commands but the 2nd is flagged as
1797 * - ( as the first character just ups the bracket depth
1798 * - unquoted ) when bracket depth > 0 terminates a bracket and
1799 * adds a CMD_LIST structure with null command
1800 * - Anything else gets put into the command string (including
1803 WCHAR
*WCMD_ReadAndParseLine(const WCHAR
*optionalcmd
, CMD_LIST
**output
, HANDLE readFrom
)
1807 WCHAR curString
[MAXSTRING
];
1808 int curStringLen
= 0;
1809 WCHAR curRedirs
[MAXSTRING
];
1810 int curRedirsLen
= 0;
1814 CMD_LIST
*lastEntry
= NULL
;
1815 CMD_DELIMITERS prevDelim
= CMD_NONE
;
1816 static WCHAR
*extraSpace
= NULL
; /* Deliberately never freed */
1817 BOOL inOneLine
= FALSE
;
1822 BOOL onlyWhiteSpace
= FALSE
;
1823 BOOL lastWasWhiteSpace
= FALSE
;
1824 BOOL lastWasDo
= FALSE
;
1825 BOOL lastWasIn
= FALSE
;
1826 BOOL lastWasElse
= FALSE
;
1827 BOOL lastWasRedirect
= TRUE
;
1828 BOOL lastWasCaret
= FALSE
;
1829 BOOL ignoreBracket
= FALSE
; /* Some expressions after if (set) require */
1830 /* handling brackets as a normal character */
1831 int lineCurDepth
; /* Bracket depth when line was read in */
1832 BOOL resetAtEndOfLine
= FALSE
; /* Do we need to reset curdepth at EOL */
1834 /* Allocate working space for a command read from keyboard, file etc */
1836 extraSpace
= heap_xalloc((MAXSTRING
+1) * sizeof(WCHAR
));
1839 WINE_ERR("Could not allocate memory for extraSpace\n");
1843 /* If initial command read in, use that, otherwise get input from handle */
1844 if (optionalcmd
!= NULL
) {
1845 lstrcpyW(extraSpace
, optionalcmd
);
1846 } else if (readFrom
== INVALID_HANDLE_VALUE
) {
1847 WINE_FIXME("No command nor handle supplied\n");
1849 if (!WCMD_fgets(extraSpace
, MAXSTRING
, readFrom
))
1852 curPos
= extraSpace
;
1854 /* Handle truncated input - issue warning */
1855 if (lstrlenW(extraSpace
) == MAXSTRING
-1) {
1856 WCMD_output_asis_stderr(WCMD_LoadMessage(WCMD_TRUNCATEDLINE
));
1857 WCMD_output_asis_stderr(extraSpace
);
1858 WCMD_output_asis_stderr(L
"\r\n");
1861 /* Replace env vars if in a batch context */
1862 if (context
) handleExpansion(extraSpace
, FALSE
, FALSE
);
1864 /* Skip preceding whitespace */
1865 while (*curPos
== ' ' || *curPos
== '\t') curPos
++;
1867 /* Show prompt before batch line IF echo is on and in batch program */
1868 if (context
&& echo_mode
&& *curPos
&& (*curPos
!= '@')) {
1869 const DWORD len
= lstrlenW(L
"echo.");
1870 DWORD curr_size
= lstrlenW(curPos
);
1871 DWORD min_len
= (curr_size
< len
? curr_size
: len
);
1872 WCMD_show_prompt(TRUE
);
1873 WCMD_output_asis(curPos
);
1874 /* I don't know why Windows puts a space here but it does */
1875 /* Except for lines starting with 'echo.', 'echo:' or 'echo/'. Ask MS why */
1876 if (CompareStringW(LOCALE_SYSTEM_DEFAULT
, NORM_IGNORECASE
,
1877 curPos
, min_len
, L
"echo.", len
) != CSTR_EQUAL
1878 && CompareStringW(LOCALE_SYSTEM_DEFAULT
, NORM_IGNORECASE
,
1879 curPos
, min_len
, L
"echo:", len
) != CSTR_EQUAL
1880 && CompareStringW(LOCALE_SYSTEM_DEFAULT
, NORM_IGNORECASE
,
1881 curPos
, min_len
, L
"echo/", len
) != CSTR_EQUAL
)
1883 WCMD_output_asis(L
" ");
1885 WCMD_output_asis(L
"\r\n");
1888 /* Skip repeated 'no echo' characters */
1889 while (*curPos
== '@') curPos
++;
1891 /* Start with an empty string, copying to the command string */
1894 curCopyTo
= curString
;
1895 curLen
= &curStringLen
;
1896 lastWasRedirect
= FALSE
; /* Required e.g. for spaces between > and filename */
1897 lineCurDepth
= curDepth
; /* What was the curdepth at the beginning of the line */
1899 /* Parse every character on the line being processed */
1900 while (*curPos
!= 0x00) {
1905 WINE_TRACE("Looking at '%c' (len:%d, lws:%d, ows:%d)\n", *curPos, *curLen,
1906 lastWasWhiteSpace, onlyWhiteSpace);
1909 /* Prevent overflow caused by the caret escape char */
1910 if (*curLen
>= MAXSTRING
) {
1911 WINE_ERR("Overflow detected in command\n");
1915 /* Certain commands need special handling */
1916 if (curStringLen
== 0 && curCopyTo
== curString
) {
1917 /* If command starts with 'rem ' or identifies a label, ignore any &&, ( etc. */
1918 if (WCMD_keyword_ws_found(L
"rem", curPos
) || *curPos
== ':') {
1921 } else if (WCMD_keyword_ws_found(L
"for", curPos
)) {
1924 /* If command starts with 'if ' or 'else ', handle ('s mid line. We should ensure this
1925 is only true in the command portion of the IF statement, but this
1926 should suffice for now.
1927 To be able to handle ('s in the condition part take as much as evaluate_if_condition
1928 would take and skip parsing it here. */
1929 } else if (WCMD_keyword_ws_found(L
"if", curPos
)) {
1930 int negate
; /* Negate condition */
1931 int test
; /* Condition evaluation result */
1936 p
= curPos
+(lstrlenW(L
"if"));
1937 while (*p
== ' ' || *p
== '\t')
1939 WCMD_parse (p
, quals
, param1
, param2
);
1941 /* Function evaluate_if_condition relies on the global variables quals, param1 and param2
1942 set in a call to WCMD_parse before */
1943 if (evaluate_if_condition(p
, &command
, &test
, &negate
) != -1)
1945 int if_condition_len
= command
- curPos
;
1946 WINE_TRACE("p: %s, quals: %s, param1: %s, param2: %s, command: %s, if_condition_len: %d\n",
1947 wine_dbgstr_w(p
), wine_dbgstr_w(quals
), wine_dbgstr_w(param1
),
1948 wine_dbgstr_w(param2
), wine_dbgstr_w(command
), if_condition_len
);
1949 memcpy(&curCopyTo
[*curLen
], curPos
, if_condition_len
*sizeof(WCHAR
));
1950 (*curLen
)+=if_condition_len
;
1951 curPos
+=if_condition_len
;
1954 if (WCMD_keyword_ws_found(L
"set", curPos
))
1955 ignoreBracket
= TRUE
;
1957 } else if (WCMD_keyword_ws_found(L
"else", curPos
)) {
1958 const int keyw_len
= lstrlenW(L
"else") + 1;
1961 onlyWhiteSpace
= TRUE
;
1962 memcpy(&curCopyTo
[*curLen
], curPos
, keyw_len
*sizeof(WCHAR
));
1963 (*curLen
)+=keyw_len
;
1966 /* If we had a single line if XXX which reaches an else (needs odd
1967 syntax like if 1=1 command && (command) else command we pretended
1968 to add brackets for the if, so they are now over */
1969 if (resetAtEndOfLine
) {
1970 WINE_TRACE("Resetting curdepth at end of line to %d\n", lineCurDepth
);
1971 resetAtEndOfLine
= FALSE
;
1972 curDepth
= lineCurDepth
;
1976 /* In a for loop, the DO command will follow a close bracket followed by
1977 whitespace, followed by DO, ie closeBracket inserts a NULL entry, curLen
1978 is then 0, and all whitespace is skipped */
1979 } else if (inFor
&& WCMD_keyword_ws_found(L
"do", curPos
)) {
1980 const int keyw_len
= lstrlenW(L
"do") + 1;
1981 WINE_TRACE("Found 'DO '\n");
1983 onlyWhiteSpace
= TRUE
;
1984 memcpy(&curCopyTo
[*curLen
], curPos
, keyw_len
*sizeof(WCHAR
));
1985 (*curLen
)+=keyw_len
;
1989 } else if (curCopyTo
== curString
) {
1991 /* Special handling for the 'FOR' command */
1992 if (inFor
&& lastWasWhiteSpace
) {
1993 WINE_TRACE("Found 'FOR ', comparing next parm: '%s'\n", wine_dbgstr_w(curPos
));
1995 if (WCMD_keyword_ws_found(L
"in", curPos
)) {
1996 const int keyw_len
= lstrlenW(L
"in") + 1;
1997 WINE_TRACE("Found 'IN '\n");
1999 onlyWhiteSpace
= TRUE
;
2000 memcpy(&curCopyTo
[*curLen
], curPos
, keyw_len
*sizeof(WCHAR
));
2001 (*curLen
)+=keyw_len
;
2008 /* Nothing 'ends' a one line statement (e.g. REM or :labels mean
2009 the &&, quotes and redirection etc are ineffective, so just force
2010 the use of the default processing by skipping character specific
2012 if (!inOneLine
) thisChar
= *curPos
;
2013 else thisChar
= 'X'; /* Character with no special processing */
2015 lastWasWhiteSpace
= FALSE
; /* Will be reset below */
2016 lastWasCaret
= FALSE
;
2020 case '=': /* drop through - ignore token delimiters at the start of a command */
2021 case ',': /* drop through - ignore token delimiters at the start of a command */
2022 case '\t':/* drop through - ignore token delimiters at the start of a command */
2024 /* If a redirect in place, it ends here */
2025 if (!inQuotes
&& !lastWasRedirect
) {
2027 /* If finishing off a redirect, add a whitespace delimiter */
2028 if (curCopyTo
== curRedirs
) {
2029 curCopyTo
[(*curLen
)++] = ' ';
2031 curCopyTo
= curString
;
2032 curLen
= &curStringLen
;
2035 curCopyTo
[(*curLen
)++] = *curPos
;
2038 /* Remember just processed whitespace */
2039 lastWasWhiteSpace
= TRUE
;
2043 case '>': /* drop through - handle redirect chars the same */
2045 /* Make a redirect start here */
2047 curCopyTo
= curRedirs
;
2048 curLen
= &curRedirsLen
;
2049 lastWasRedirect
= TRUE
;
2052 /* See if 1>, 2> etc, in which case we have some patching up
2053 to do (provided there's a preceding whitespace, and enough
2054 chars read so far) */
2055 if (curStringLen
> 2
2056 && (*(curPos
-1)>='1') && (*(curPos
-1)<='9')
2057 && ((*(curPos
-2)==' ') || (*(curPos
-2)=='\t'))) {
2059 curString
[curStringLen
] = 0x00;
2060 curCopyTo
[(*curLen
)++] = *(curPos
-1);
2063 curCopyTo
[(*curLen
)++] = *curPos
;
2065 /* If a redirect is immediately followed by '&' (ie. 2>&1) then
2066 do not process that ampersand as an AND operator */
2067 if (thisChar
== '>' && *(curPos
+1) == '&') {
2068 curCopyTo
[(*curLen
)++] = *(curPos
+1);
2073 case '|': /* Pipe character only if not || */
2075 lastWasRedirect
= FALSE
;
2077 /* Add an entry to the command list */
2078 if (curStringLen
> 0) {
2080 /* Add the current command */
2081 WCMD_addCommand(curString
, &curStringLen
,
2082 curRedirs
, &curRedirsLen
,
2083 &curCopyTo
, &curLen
,
2084 prevDelim
, curDepth
,
2085 &lastEntry
, output
);
2089 if (*(curPos
+1) == '|') {
2090 curPos
++; /* Skip other | */
2091 prevDelim
= CMD_ONFAILURE
;
2093 prevDelim
= CMD_PIPE
;
2096 /* If in an IF or ELSE statement, put subsequent chained
2097 commands at a higher depth as if brackets were supplied
2098 but remember to reset to the original depth at EOL */
2099 if ((inIf
|| inElse
) && curDepth
== lineCurDepth
) {
2101 resetAtEndOfLine
= TRUE
;
2104 curCopyTo
[(*curLen
)++] = *curPos
;
2108 case '"': if (WCMD_IsEndQuote(curPos
, inQuotes
)) {
2111 inQuotes
++; /* Quotes within quotes are fun! */
2113 curCopyTo
[(*curLen
)++] = *curPos
;
2114 lastWasRedirect
= FALSE
;
2117 case '(': /* If a '(' is the first non whitespace in a command portion
2118 ie start of line or just after &&, then we read until an
2119 unquoted ) is found */
2120 WINE_TRACE("Found '(' conditions: curLen(%d), inQ(%d), onlyWS(%d)"
2121 ", for(%d, In:%d, Do:%d)"
2122 ", if(%d, else:%d, lwe:%d)\n",
2125 inFor
, lastWasIn
, lastWasDo
,
2126 inIf
, inElse
, lastWasElse
);
2127 lastWasRedirect
= FALSE
;
2129 /* Ignore open brackets inside the for set */
2130 if (*curLen
== 0 && !inIn
) {
2133 /* If in quotes, ignore brackets */
2134 } else if (inQuotes
) {
2135 curCopyTo
[(*curLen
)++] = *curPos
;
2137 /* In a FOR loop, an unquoted '(' may occur straight after
2139 In an IF statement just handle it regardless as we don't
2141 In an ELSE statement, only allow it straight away after
2142 the ELSE and whitespace
2144 } else if ((inIf
&& !ignoreBracket
) ||
2145 (inElse
&& lastWasElse
&& onlyWhiteSpace
) ||
2146 (inFor
&& (lastWasIn
|| lastWasDo
) && onlyWhiteSpace
)) {
2148 /* If entering into an 'IN', set inIn */
2149 if (inFor
&& lastWasIn
&& onlyWhiteSpace
) {
2150 WINE_TRACE("Inside an IN\n");
2154 /* Add the current command */
2155 WCMD_addCommand(curString
, &curStringLen
,
2156 curRedirs
, &curRedirsLen
,
2157 &curCopyTo
, &curLen
,
2158 prevDelim
, curDepth
,
2159 &lastEntry
, output
);
2163 curCopyTo
[(*curLen
)++] = *curPos
;
2167 case '^': if (!inQuotes
) {
2168 /* If we reach the end of the input, we need to wait for more */
2169 if (*(curPos
+1) == 0x00) {
2170 lastWasCaret
= TRUE
;
2171 WINE_TRACE("Caret found at end of line\n");
2176 curCopyTo
[(*curLen
)++] = *curPos
;
2179 case '&': if (!inQuotes
) {
2180 lastWasRedirect
= FALSE
;
2182 /* Add an entry to the command list */
2183 if (curStringLen
> 0) {
2185 /* Add the current command */
2186 WCMD_addCommand(curString
, &curStringLen
,
2187 curRedirs
, &curRedirsLen
,
2188 &curCopyTo
, &curLen
,
2189 prevDelim
, curDepth
,
2190 &lastEntry
, output
);
2194 if (*(curPos
+1) == '&') {
2195 curPos
++; /* Skip other & */
2196 prevDelim
= CMD_ONSUCCESS
;
2198 prevDelim
= CMD_NONE
;
2200 /* If in an IF or ELSE statement, put subsequent chained
2201 commands at a higher depth as if brackets were supplied
2202 but remember to reset to the original depth at EOL */
2203 if ((inIf
|| inElse
) && curDepth
== lineCurDepth
) {
2205 resetAtEndOfLine
= TRUE
;
2208 curCopyTo
[(*curLen
)++] = *curPos
;
2212 case ')': if (!inQuotes
&& curDepth
> 0) {
2213 lastWasRedirect
= FALSE
;
2215 /* Add the current command if there is one */
2218 /* Add the current command */
2219 WCMD_addCommand(curString
, &curStringLen
,
2220 curRedirs
, &curRedirsLen
,
2221 &curCopyTo
, &curLen
,
2222 prevDelim
, curDepth
,
2223 &lastEntry
, output
);
2226 /* Add an empty entry to the command list */
2227 prevDelim
= CMD_NONE
;
2228 WCMD_addCommand(NULL
, &curStringLen
,
2229 curRedirs
, &curRedirsLen
,
2230 &curCopyTo
, &curLen
,
2231 prevDelim
, curDepth
,
2232 &lastEntry
, output
);
2235 /* Leave inIn if necessary */
2236 if (inIn
) inIn
= FALSE
;
2238 curCopyTo
[(*curLen
)++] = *curPos
;
2242 lastWasRedirect
= FALSE
;
2243 curCopyTo
[(*curLen
)++] = *curPos
;
2248 /* At various times we need to know if we have only skipped whitespace,
2249 so reset this variable and then it will remain true until a non
2250 whitespace is found */
2251 if ((thisChar
!= ' ') && (thisChar
!= '\t') && (thisChar
!= '\n'))
2252 onlyWhiteSpace
= FALSE
;
2254 /* Flag end of interest in FOR DO and IN parms once something has been processed */
2255 if (!lastWasWhiteSpace
) {
2256 lastWasIn
= lastWasDo
= FALSE
;
2259 /* If we have reached the end, add this command into the list
2260 Do not add command to list if escape char ^ was last */
2261 if (*curPos
== 0x00 && !lastWasCaret
&& *curLen
> 0) {
2263 /* Add an entry to the command list */
2264 WCMD_addCommand(curString
, &curStringLen
,
2265 curRedirs
, &curRedirsLen
,
2266 &curCopyTo
, &curLen
,
2267 prevDelim
, curDepth
,
2268 &lastEntry
, output
);
2270 /* If we had a single line if or else, and we pretended to add
2271 brackets, end them now */
2272 if (resetAtEndOfLine
) {
2273 WINE_TRACE("Resetting curdepth at end of line to %d\n", lineCurDepth
);
2274 resetAtEndOfLine
= FALSE
;
2275 curDepth
= lineCurDepth
;
2279 /* If we have reached the end of the string, see if bracketing or
2280 final caret is outstanding */
2281 if (*curPos
== 0x00 && (curDepth
> 0 || lastWasCaret
) &&
2282 readFrom
!= INVALID_HANDLE_VALUE
) {
2285 WINE_TRACE("Need to read more data as outstanding brackets or carets\n");
2287 prevDelim
= CMD_NONE
;
2289 memset(extraSpace
, 0x00, (MAXSTRING
+1) * sizeof(WCHAR
));
2290 extraData
= extraSpace
;
2292 /* Read more, skipping any blank lines */
2294 WINE_TRACE("Read more input\n");
2295 if (!context
) WCMD_output_asis( WCMD_LoadMessage(WCMD_MOREPROMPT
));
2296 if (!WCMD_fgets(extraData
, MAXSTRING
, readFrom
))
2299 /* Edge case for carets - a completely blank line (i.e. was just
2300 CRLF) is oddly added as an LF but then more data is received (but
2303 if (*extraSpace
== 0x00) {
2304 WINE_TRACE("Read nothing, so appending LF char and will try again\n");
2305 *extraData
++ = '\r';
2310 } while (*extraData
== 0x00);
2311 curPos
= extraSpace
;
2313 /* Skip preceding whitespace */
2314 while (*curPos
== ' ' || *curPos
== '\t') curPos
++;
2316 /* Replace env vars if in a batch context */
2317 if (context
) handleExpansion(curPos
, FALSE
, FALSE
);
2319 /* Continue to echo commands IF echo is on and in batch program */
2320 if (context
&& echo_mode
&& *curPos
&& *curPos
!= '@') {
2321 WCMD_output_asis(extraSpace
);
2322 WCMD_output_asis(L
"\r\n");
2325 /* Skip repeated 'no echo' characters and whitespace */
2326 while (*curPos
== '@' || *curPos
== ' ' || *curPos
== '\t') curPos
++;
2330 /* Dump out the parsed output */
2331 WCMD_DumpCommands(*output
);
2336 /***************************************************************************
2337 * WCMD_process_commands
2339 * Process all the commands read in so far
2341 CMD_LIST
*WCMD_process_commands(CMD_LIST
*thisCmd
, BOOL oneBracket
,
2346 if (thisCmd
&& oneBracket
) bdepth
= thisCmd
->bracketDepth
;
2348 /* Loop through the commands, processing them one by one */
2351 CMD_LIST
*origCmd
= thisCmd
;
2353 /* If processing one bracket only, and we find the end bracket
2354 entry (or less), return */
2355 if (oneBracket
&& !thisCmd
->command
&&
2356 bdepth
<= thisCmd
->bracketDepth
) {
2357 WINE_TRACE("Finished bracket @ %p, next command is %p\n",
2358 thisCmd
, thisCmd
->nextcommand
);
2359 return thisCmd
->nextcommand
;
2362 /* Ignore the NULL entries a ')' inserts (Only 'if' cares
2363 about them and it will be handled in there)
2364 Also, skip over any batch labels (eg. :fred) */
2365 if (thisCmd
->command
&& thisCmd
->command
[0] != ':') {
2366 WINE_TRACE("Executing command: '%s'\n", wine_dbgstr_w(thisCmd
->command
));
2367 WCMD_execute (thisCmd
->command
, thisCmd
->redirects
, &thisCmd
, retrycall
);
2370 /* Step on unless the command itself already stepped on */
2371 if (thisCmd
== origCmd
) thisCmd
= thisCmd
->nextcommand
;
2376 /***************************************************************************
2377 * WCMD_free_commands
2379 * Frees the storage held for a parsed command line
2380 * - This is not done in the process_commands, as eventually the current
2381 * pointer will be modified within the commands, and hence a single free
2382 * routine is simpler
2384 void WCMD_free_commands(CMD_LIST
*cmds
) {
2386 /* Loop through the commands, freeing them one by one */
2388 CMD_LIST
*thisCmd
= cmds
;
2389 cmds
= cmds
->nextcommand
;
2390 heap_free(thisCmd
->command
);
2391 heap_free(thisCmd
->redirects
);
2397 /*****************************************************************************
2398 * Main entry point. This is a console application so we have a main() not a
2402 int __cdecl
wmain (int argc
, WCHAR
*argvW
[])
2404 WCHAR
*cmdLine
= NULL
;
2408 BOOL promptNewLine
= TRUE
;
2411 WCHAR comspec
[MAX_PATH
];
2412 CMD_LIST
*toExecute
= NULL
; /* Commands left to be executed */
2413 RTL_OSVERSIONINFOEXW osv
;
2415 STARTUPINFOW startupInfo
;
2418 if (!GetEnvironmentVariableW(L
"COMSPEC", comspec
, ARRAY_SIZE(comspec
)))
2420 GetSystemDirectoryW(comspec
, ARRAY_SIZE(comspec
) - ARRAY_SIZE(L
"\\cmd.exe"));
2421 lstrcatW(comspec
, L
"\\cmd.exe");
2422 SetEnvironmentVariableW(L
"COMSPEC", comspec
);
2427 /* Get the windows version being emulated */
2428 osv
.dwOSVersionInfoSize
= sizeof(osv
);
2429 RtlGetVersion(&osv
);
2431 /* Pre initialize some messages */
2432 lstrcpyW(anykey
, WCMD_LoadMessage(WCMD_ANYKEY
));
2433 sprintf(osver
, "%d.%d.%d", osv
.dwMajorVersion
, osv
.dwMinorVersion
, osv
.dwBuildNumber
);
2434 cmd
= WCMD_format_string(WCMD_LoadMessage(WCMD_VERSION
), osver
);
2435 lstrcpyW(version_string
, cmd
);
2439 /* Can't use argc/argv as it will have stripped quotes from parameters
2440 * meaning cmd.exe /C echo "quoted string" is impossible
2442 cmdLine
= GetCommandLineW();
2443 WINE_TRACE("Full commandline '%s'\n", wine_dbgstr_w(cmdLine
));
2445 while (*cmdLine
&& *cmdLine
!= '/') ++cmdLine
;
2447 opt_c
= opt_k
= opt_q
= opt_s
= FALSE
;
2449 for (arg
= cmdLine
; *arg
; ++arg
)
2454 switch (towlower(arg
[1]))
2457 unicodeOutput
= FALSE
;
2473 opt_t
= wcstoul(&arg
[3], NULL
, 16);
2476 unicodeOutput
= TRUE
;
2480 delayedsubst
= wcsnicmp(&arg
[3], L
"OFF", 3);
2491 while (*arg
&& wcschr(L
" \t,=;", *arg
)) arg
++;
2497 /* Until we start to read from the keyboard, stay as non-interactive */
2498 interactive
= FALSE
;
2500 SetEnvironmentVariableW(L
"PROMPT", L
"$P$G");
2502 if (opt_c
|| opt_k
) {
2504 WCHAR
*q1
= NULL
,*q2
= NULL
,*p
;
2507 cmd
= heap_strdupW(arg
);
2509 /* opt_s left unflagged if the command starts with and contains exactly
2510 * one quoted string (exactly two quote characters). The quoted string
2511 * must be an executable name that has whitespace and must not have the
2512 * following characters: &<>()@^| */
2515 /* 1. Confirm there is at least one quote */
2516 q1
= wcschr(arg
, '"');
2521 /* 2. Confirm there is a second quote */
2522 q2
= wcschr(q1
+1, '"');
2527 /* 3. Ensure there are no more quotes */
2528 if (wcschr(q2
+1, '"')) opt_s
=1;
2531 /* check first parameter for a space and invalid characters. There must not be any
2532 * invalid characters, but there must be one or more whitespace */
2537 if (*p
=='&' || *p
=='<' || *p
=='>' || *p
=='(' || *p
==')'
2538 || *p
=='@' || *p
=='^' || *p
=='|') {
2542 if (*p
==' ' || *p
=='\t')
2548 WINE_TRACE("/c command line: '%s'\n", wine_dbgstr_w(cmd
));
2550 /* Finally, we only stay in new mode IF the first parameter is quoted and
2551 is a valid executable, i.e. must exist, otherwise drop back to old mode */
2553 WCHAR
*thisArg
= WCMD_parameter(cmd
, 0, NULL
, FALSE
, TRUE
);
2554 WCHAR pathext
[MAXSTRING
];
2557 /* Now extract PATHEXT */
2558 len
= GetEnvironmentVariableW(L
"PATHEXT", pathext
, ARRAY_SIZE(pathext
));
2559 if ((len
== 0) || (len
>= ARRAY_SIZE(pathext
))) {
2560 lstrcpyW(pathext
, L
".bat;.com;.cmd;.exe");
2563 /* If the supplied parameter has any directory information, look there */
2564 WINE_TRACE("First parameter is '%s'\n", wine_dbgstr_w(thisArg
));
2565 if (wcschr(thisArg
, '\\') != NULL
) {
2567 GetFullPathNameW(thisArg
, ARRAY_SIZE(string
), string
, NULL
);
2568 WINE_TRACE("Full path name '%s'\n", wine_dbgstr_w(string
));
2569 p
= string
+ lstrlenW(string
);
2571 /* Does file exist with this name? */
2572 if (GetFileAttributesW(string
) != INVALID_FILE_ATTRIBUTES
) {
2573 WINE_TRACE("Found file as '%s'\n", wine_dbgstr_w(string
));
2576 WCHAR
*thisExt
= pathext
;
2578 /* No - try with each of the PATHEXT extensions */
2579 while (!found
&& thisExt
) {
2580 WCHAR
*nextExt
= wcschr(thisExt
, ';');
2583 memcpy(p
, thisExt
, (nextExt
-thisExt
) * sizeof(WCHAR
));
2584 p
[(nextExt
-thisExt
)] = 0x00;
2585 thisExt
= nextExt
+1;
2587 lstrcpyW(p
, thisExt
);
2591 /* Does file exist with this extension appended? */
2592 if (GetFileAttributesW(string
) != INVALID_FILE_ATTRIBUTES
) {
2593 WINE_TRACE("Found file as '%s'\n", wine_dbgstr_w(string
));
2599 /* Otherwise we now need to look in the path to see if we can find it */
2601 /* Does file exist with this name? */
2602 if (SearchPathW(NULL
, thisArg
, NULL
, ARRAY_SIZE(string
), string
, NULL
) != 0) {
2603 WINE_TRACE("Found on path as '%s'\n", wine_dbgstr_w(string
));
2606 WCHAR
*thisExt
= pathext
;
2608 /* No - try with each of the PATHEXT extensions */
2609 while (!found
&& thisExt
) {
2610 WCHAR
*nextExt
= wcschr(thisExt
, ';');
2614 nextExt
= nextExt
+1;
2619 /* Does file exist with this extension? */
2620 if (SearchPathW(NULL
, thisArg
, thisExt
, ARRAY_SIZE(string
), string
, NULL
) != 0) {
2621 WINE_TRACE("Found on path as '%s' with extension '%s'\n", wine_dbgstr_w(string
),
2622 wine_dbgstr_w(thisExt
));
2630 /* If not found, drop back to old behaviour */
2632 WINE_TRACE("Binary not found, dropping back to old behaviour\n");
2638 /* strip first and last quote characters if opt_s; check for invalid
2639 * executable is done later */
2640 if (opt_s
&& *cmd
=='\"')
2641 WCMD_strip_quotes(cmd
);
2644 /* Save cwd into appropriate env var (Must be before the /c processing */
2645 GetCurrentDirectoryW(ARRAY_SIZE(string
), string
);
2646 if (IsCharAlphaW(string
[0]) && string
[1] == ':') {
2647 wsprintfW(envvar
, L
"=%c:", string
[0]);
2648 SetEnvironmentVariableW(envvar
, string
);
2649 WINE_TRACE("Set %s to %s\n", wine_dbgstr_w(envvar
), wine_dbgstr_w(string
));
2653 /* If we do a "cmd /c command", we don't want to allocate a new
2654 * console since the command returns immediately. Rather, we use
2655 * the currently allocated input and output handles. This allows
2656 * us to pipe to and read from the command interpreter.
2659 /* Parse the command string, without reading any more input */
2660 WCMD_ReadAndParseLine(cmd
, &toExecute
, INVALID_HANDLE_VALUE
);
2661 WCMD_process_commands(toExecute
, FALSE
, FALSE
);
2662 WCMD_free_commands(toExecute
);
2669 GetStartupInfoW(&startupInfo
);
2670 if (startupInfo
.lpTitle
!= NULL
)
2671 SetConsoleTitleW(startupInfo
.lpTitle
);
2673 SetConsoleTitleW(WCMD_LoadMessage(WCMD_CONSTITLE
));
2675 /* Note: cmd.exe /c dir does not get a new color, /k dir does */
2677 if (!(((opt_t
& 0xF0) >> 4) == (opt_t
& 0x0F))) {
2678 defaultColor
= opt_t
& 0xFF;
2683 /* Check HKCU\Software\Microsoft\Command Processor
2684 Then HKLM\Software\Microsoft\Command Processor
2685 for defaultcolour value
2686 Note Can be supplied as DWORD or REG_SZ
2687 Note2 When supplied as REG_SZ it's in decimal!!! */
2690 DWORD value
=0, size
=4;
2691 static const WCHAR regKeyW
[] = L
"Software\\Microsoft\\Command Processor";
2693 if (RegOpenKeyExW(HKEY_CURRENT_USER
, regKeyW
,
2694 0, KEY_READ
, &key
) == ERROR_SUCCESS
) {
2697 /* See if DWORD or REG_SZ */
2698 if (RegQueryValueExW(key
, L
"DefaultColor", NULL
, &type
, NULL
, NULL
) == ERROR_SUCCESS
) {
2699 if (type
== REG_DWORD
) {
2700 size
= sizeof(DWORD
);
2701 RegQueryValueExW(key
, L
"DefaultColor", NULL
, NULL
, (BYTE
*)&value
, &size
);
2702 } else if (type
== REG_SZ
) {
2703 size
= ARRAY_SIZE(strvalue
);
2704 RegQueryValueExW(key
, L
"DefaultColor", NULL
, NULL
, (BYTE
*)strvalue
, &size
);
2705 value
= wcstoul(strvalue
, NULL
, 10);
2711 if (value
== 0 && RegOpenKeyExW(HKEY_LOCAL_MACHINE
, regKeyW
,
2712 0, KEY_READ
, &key
) == ERROR_SUCCESS
) {
2715 /* See if DWORD or REG_SZ */
2716 if (RegQueryValueExW(key
, L
"DefaultColor", NULL
, &type
,
2717 NULL
, NULL
) == ERROR_SUCCESS
) {
2718 if (type
== REG_DWORD
) {
2719 size
= sizeof(DWORD
);
2720 RegQueryValueExW(key
, L
"DefaultColor", NULL
, NULL
, (BYTE
*)&value
, &size
);
2721 } else if (type
== REG_SZ
) {
2722 size
= ARRAY_SIZE(strvalue
);
2723 RegQueryValueExW(key
, L
"DefaultColor", NULL
, NULL
, (BYTE
*)strvalue
, &size
);
2724 value
= wcstoul(strvalue
, NULL
, 10);
2730 /* If one found, set the screen to that colour */
2731 if (!(((value
& 0xF0) >> 4) == (value
& 0x0F))) {
2732 defaultColor
= value
& 0xFF;
2740 /* Parse the command string, without reading any more input */
2741 WCMD_ReadAndParseLine(cmd
, &toExecute
, INVALID_HANDLE_VALUE
);
2742 WCMD_process_commands(toExecute
, FALSE
, FALSE
);
2743 WCMD_free_commands(toExecute
);
2749 * Loop forever getting commands and executing them.
2753 if (!opt_k
) WCMD_version ();
2756 /* Read until EOF (which for std input is never, but if redirect
2757 in place, may occur */
2758 if (echo_mode
) WCMD_show_prompt(promptNewLine
);
2759 if (!WCMD_ReadAndParseLine(NULL
, &toExecute
, GetStdHandle(STD_INPUT_HANDLE
)))
2761 WCMD_process_commands(toExecute
, FALSE
, FALSE
);
2762 WCMD_free_commands(toExecute
);
2763 promptNewLine
= !!toExecute
;