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
30 #include "wine/debug.h"
32 WINE_DEFAULT_DEBUG_CHANNEL(cmd
);
34 extern const WCHAR inbuilt
[][10];
35 extern struct env_stack
*pushd_directories
;
37 BATCH_CONTEXT
*context
= NULL
;
39 WCHAR quals
[MAX_PATH
], param1
[MAXSTRING
], param2
[MAXSTRING
];
42 BOOL echo_mode
= TRUE
;
44 WCHAR anykey
[100], version_string
[100];
45 const WCHAR newline
[] = {'\r','\n','\0'};
46 const WCHAR space
[] = {' ','\0'};
48 static BOOL opt_c
, opt_k
, opt_s
, unicodeOutput
= FALSE
;
50 /* Variables pertaining to paging */
51 static BOOL paged_mode
;
52 static const WCHAR
*pagedMessage
= NULL
;
53 static int line_count
;
54 static int max_height
;
58 #define MAX_WRITECONSOLE_SIZE 65535
61 * Returns a buffer for reading from/writing to file
64 static char *get_file_buffer(void)
66 static char *output_bufA
= NULL
;
68 output_bufA
= HeapAlloc(GetProcessHeap(), 0, MAX_WRITECONSOLE_SIZE
);
70 WINE_FIXME("Out of memory - could not allocate ansi 64K buffer\n");
75 /*******************************************************************
76 * WCMD_output_asis_len - send output to current standard output
78 * Output a formatted unicode string. Ideally this will go to the console
79 * and hence required WriteConsoleW to output it, however if file i/o is
80 * redirected, it needs to be WriteFile'd using OEM (not ANSI) format
82 static void WCMD_output_asis_len(const WCHAR
*message
, DWORD len
, HANDLE device
)
87 /* If nothing to write, return (MORE does this sometimes) */
90 /* Try to write as unicode assuming it is to a console */
91 res
= WriteConsoleW(device
, message
, len
, &nOut
, NULL
);
93 /* If writing to console fails, assume its file
94 i/o so convert to OEM codepage and output */
96 BOOL usedDefaultChar
= FALSE
;
100 if (!unicodeOutput
) {
102 if (!(buffer
= get_file_buffer()))
105 /* Convert to OEM, then output */
106 convertedChars
= WideCharToMultiByte(GetConsoleOutputCP(), 0, message
,
107 len
, buffer
, MAX_WRITECONSOLE_SIZE
,
108 "?", &usedDefaultChar
);
109 WriteFile(device
, buffer
, convertedChars
,
112 WriteFile(device
, message
, len
*sizeof(WCHAR
),
119 /*******************************************************************
120 * WCMD_output - send output to current standard output device.
124 void CDECL
WCMD_output (const WCHAR
*format
, ...) {
130 __ms_va_start(ap
,format
);
131 SetLastError(NO_ERROR
);
133 len
= FormatMessageW(FORMAT_MESSAGE_FROM_STRING
|FORMAT_MESSAGE_ALLOCATE_BUFFER
,
134 format
, 0, 0, (LPWSTR
)&string
, 0, &ap
);
136 if (len
== 0 && GetLastError() != NO_ERROR
)
137 WINE_FIXME("Could not format string: le=%u, fmt=%s\n", GetLastError(), wine_dbgstr_w(format
));
140 WCMD_output_asis_len(string
, len
, GetStdHandle(STD_OUTPUT_HANDLE
));
145 /*******************************************************************
146 * WCMD_output_stderr - send output to current standard error device.
150 void CDECL
WCMD_output_stderr (const WCHAR
*format
, ...) {
156 __ms_va_start(ap
,format
);
157 SetLastError(NO_ERROR
);
159 len
= FormatMessageW(FORMAT_MESSAGE_FROM_STRING
|FORMAT_MESSAGE_ALLOCATE_BUFFER
,
160 format
, 0, 0, (LPWSTR
)&string
, 0, &ap
);
162 if (len
== 0 && GetLastError() != NO_ERROR
)
163 WINE_FIXME("Could not format string: le=%u, fmt=%s\n", GetLastError(), wine_dbgstr_w(format
));
166 WCMD_output_asis_len(string
, len
, GetStdHandle(STD_ERROR_HANDLE
));
171 /*******************************************************************
172 * WCMD_format_string - allocate a buffer and format a string
176 WCHAR
* CDECL
WCMD_format_string (const WCHAR
*format
, ...) {
182 __ms_va_start(ap
,format
);
183 SetLastError(NO_ERROR
);
184 len
= FormatMessageW(FORMAT_MESSAGE_FROM_STRING
|FORMAT_MESSAGE_ALLOCATE_BUFFER
,
185 format
, 0, 0, (LPWSTR
)&string
, 0, &ap
);
187 if (len
== 0 && GetLastError() != NO_ERROR
) {
188 WINE_FIXME("Could not format string: le=%u, fmt=%s\n", GetLastError(), wine_dbgstr_w(format
));
189 string
= (WCHAR
*)LocalAlloc(LMEM_FIXED
, 2);
195 void WCMD_enter_paged_mode(const WCHAR
*msg
)
197 CONSOLE_SCREEN_BUFFER_INFO consoleInfo
;
199 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE
), &consoleInfo
)) {
200 max_height
= consoleInfo
.dwSize
.Y
;
201 max_width
= consoleInfo
.dwSize
.X
;
209 pagedMessage
= (msg
==NULL
)? anykey
: msg
;
212 void WCMD_leave_paged_mode(void)
218 /***************************************************************************
221 * Read characters in from a console/file, returning result in Unicode
223 BOOL
WCMD_ReadFile(const HANDLE hIn
, WCHAR
*intoBuf
, const DWORD maxChars
, LPDWORD charsRead
)
228 if (WCMD_is_console_handle(hIn
))
229 /* Try to read from console as Unicode */
230 return ReadConsoleW(hIn
, intoBuf
, maxChars
, charsRead
, NULL
);
232 /* We assume it's a file handle and read then convert from assumed OEM codepage */
233 if (!(buffer
= get_file_buffer()))
236 if (!ReadFile(hIn
, buffer
, maxChars
, &numRead
, NULL
))
239 *charsRead
= MultiByteToWideChar(GetConsoleCP(), 0, buffer
, numRead
, intoBuf
, maxChars
);
244 /*******************************************************************
245 * WCMD_output_asis_handle
247 * Send output to specified handle without formatting e.g. when message contains '%'
249 static void WCMD_output_asis_handle (DWORD std_handle
, const WCHAR
*message
) {
253 HANDLE handle
= GetStdHandle(std_handle
);
258 while (*ptr
&& *ptr
!='\n' && (numChars
< max_width
)) {
262 if (*ptr
== '\n') ptr
++;
263 WCMD_output_asis_len(message
, ptr
- message
, handle
);
265 if (++line_count
>= max_height
- 1) {
267 WCMD_output_asis_len(pagedMessage
, strlenW(pagedMessage
), handle
);
268 WCMD_ReadFile(GetStdHandle(STD_INPUT_HANDLE
), string
, sizeof(string
)/sizeof(WCHAR
), &count
);
270 } while (((message
= ptr
) != NULL
) && (*ptr
));
272 WCMD_output_asis_len(message
, lstrlenW(message
), handle
);
276 /*******************************************************************
279 * Send output to current standard output device, without formatting
280 * e.g. when message contains '%'
282 void WCMD_output_asis (const WCHAR
*message
) {
283 WCMD_output_asis_handle(STD_OUTPUT_HANDLE
, message
);
286 /*******************************************************************
287 * WCMD_output_asis_stderr
289 * Send output to current standard error device, without formatting
290 * e.g. when message contains '%'
292 void WCMD_output_asis_stderr (const WCHAR
*message
) {
293 WCMD_output_asis_handle(STD_ERROR_HANDLE
, message
);
296 /****************************************************************************
299 * Print the message for GetLastError
302 void WCMD_print_error (void) {
307 error_code
= GetLastError ();
308 status
= FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
,
309 NULL
, error_code
, 0, (LPWSTR
) &lpMsgBuf
, 0, NULL
);
311 WINE_FIXME ("Cannot display message for error %d, status %d\n",
312 error_code
, GetLastError());
316 WCMD_output_asis_len(lpMsgBuf
, lstrlenW(lpMsgBuf
),
317 GetStdHandle(STD_ERROR_HANDLE
));
318 LocalFree (lpMsgBuf
);
319 WCMD_output_asis_len (newline
, lstrlenW(newline
),
320 GetStdHandle(STD_ERROR_HANDLE
));
324 /******************************************************************************
327 * Display the prompt on STDout
331 static void WCMD_show_prompt (void) {
334 WCHAR out_string
[MAX_PATH
], curdir
[MAX_PATH
], prompt_string
[MAX_PATH
];
337 static const WCHAR envPrompt
[] = {'P','R','O','M','P','T','\0'};
339 len
= GetEnvironmentVariableW(envPrompt
, prompt_string
,
340 sizeof(prompt_string
)/sizeof(WCHAR
));
341 if ((len
== 0) || (len
>= (sizeof(prompt_string
)/sizeof(WCHAR
)))) {
342 static const WCHAR dfltPrompt
[] = {'$','P','$','G','\0'};
343 strcpyW (prompt_string
, dfltPrompt
);
357 switch (toupper(*p
)) {
371 GetDateFormatW(LOCALE_USER_DEFAULT
, DATE_SHORTDATE
, NULL
, NULL
, q
, MAX_PATH
);
390 status
= GetCurrentDirectoryW(sizeof(curdir
)/sizeof(WCHAR
), curdir
);
396 status
= GetCurrentDirectoryW(sizeof(curdir
)/sizeof(WCHAR
), curdir
);
409 GetTimeFormatW(LOCALE_USER_DEFAULT
, 0, NULL
, NULL
, q
, MAX_PATH
);
413 strcatW (q
, version_string
);
420 if (pushd_directories
) {
421 memset(q
, '+', pushd_directories
->u
.stackdepth
);
422 q
= q
+ pushd_directories
->u
.stackdepth
;
430 WCMD_output_asis (out_string
);
434 /*************************************************************************
436 * A wide version of strdup as its missing from unicode.h
438 WCHAR
*WCMD_strdupW(const WCHAR
*input
) {
439 int len
=strlenW(input
)+1;
440 WCHAR
*result
= HeapAlloc(GetProcessHeap(), 0, len
* sizeof(WCHAR
));
441 memcpy(result
, input
, len
* sizeof(WCHAR
));
445 /*************************************************************************
447 * Replaces a portion of a Unicode string with the specified string.
448 * It's up to the caller to ensure there is enough space in the
449 * destination buffer.
451 void WCMD_strsubstW(WCHAR
*start
, const WCHAR
*next
, const WCHAR
*insert
, int len
) {
454 len
=insert
? lstrlenW(insert
) : 0;
455 if (start
+len
!= next
)
456 memmove(start
+len
, next
, (strlenW(next
) + 1) * sizeof(*next
));
458 memcpy(start
, insert
, len
* sizeof(*insert
));
461 /***************************************************************************
462 * WCMD_skip_leading_spaces
464 * Return a pointer to the first non-whitespace character of string.
465 * Does not modify the input string.
467 WCHAR
*WCMD_skip_leading_spaces (WCHAR
*string
) {
472 while (*ptr
== ' ' || *ptr
== '\t') ptr
++;
476 /***************************************************************************
477 * WCMD_keyword_ws_found
479 * Checks if the string located at ptr matches a keyword (of length len)
480 * followed by a whitespace character (space or tab)
482 BOOL
WCMD_keyword_ws_found(const WCHAR
*keyword
, int len
, const WCHAR
*ptr
) {
483 return (CompareStringW(LOCALE_USER_DEFAULT
, NORM_IGNORECASE
| SORT_STRINGSORT
,
484 ptr
, len
, keyword
, len
) == CSTR_EQUAL
)
485 && ((*(ptr
+ len
) == ' ') || (*(ptr
+ len
) == '\t'));
488 /*************************************************************************
491 * Remove first and last quote WCHARacters, preserving all other text
493 void WCMD_strip_quotes(WCHAR
*cmd
) {
494 WCHAR
*src
= cmd
+ 1, *dest
= cmd
, *lastq
= NULL
;
495 while((*dest
=*src
) != '\0') {
502 while ((*dest
++=*lastq
++) != 0)
508 /*************************************************************************
509 * WCMD_is_magic_envvar
510 * Return TRUE if s is '%'magicvar'%'
511 * and is not masked by a real environment variable.
514 static inline BOOL
WCMD_is_magic_envvar(const WCHAR
*s
, const WCHAR
*magicvar
)
519 return FALSE
; /* Didn't begin with % */
521 if (len
< 2 || s
[len
-1] != '%')
522 return FALSE
; /* Didn't end with another % */
524 if (CompareStringW(LOCALE_USER_DEFAULT
,
525 NORM_IGNORECASE
| SORT_STRINGSORT
,
526 s
+1, len
-2, magicvar
, -1) != CSTR_EQUAL
) {
527 /* Name doesn't match. */
531 if (GetEnvironmentVariableW(magicvar
, NULL
, 0) > 0) {
532 /* Masked by real environment variable. */
539 /*************************************************************************
542 * Expands environment variables, allowing for WCHARacter substitution
544 static WCHAR
*WCMD_expand_envvar(WCHAR
*start
,
545 const WCHAR
*forVar
, const WCHAR
*forVal
) {
546 WCHAR
*endOfVar
= NULL
, *s
;
547 WCHAR
*colonpos
= NULL
;
548 WCHAR thisVar
[MAXSTRING
];
549 WCHAR thisVarContents
[MAXSTRING
];
550 WCHAR savedchar
= 0x00;
553 static const WCHAR ErrorLvl
[] = {'E','R','R','O','R','L','E','V','E','L','\0'};
554 static const WCHAR Date
[] = {'D','A','T','E','\0'};
555 static const WCHAR Time
[] = {'T','I','M','E','\0'};
556 static const WCHAR Cd
[] = {'C','D','\0'};
557 static const WCHAR Random
[] = {'R','A','N','D','O','M','\0'};
558 static const WCHAR Delims
[] = {'%',' ',':','\0'};
560 WINE_TRACE("Expanding: %s (%s,%s)\n", wine_dbgstr_w(start
),
561 wine_dbgstr_w(forVal
), wine_dbgstr_w(forVar
));
563 /* Find the end of the environment variable, and extract name */
564 endOfVar
= strpbrkW(start
+1, Delims
);
566 if (endOfVar
== NULL
|| *endOfVar
==' ') {
568 /* In batch program, missing terminator for % and no following
569 ':' just removes the '%' */
571 WCMD_strsubstW(start
, start
+ 1, NULL
, 0);
575 /* In command processing, just ignore it - allows command line
576 syntax like: for %i in (a.a) do echo %i */
581 /* If ':' found, process remaining up until '%' (or stop at ':' if
583 if (*endOfVar
==':') {
584 WCHAR
*endOfVar2
= strchrW(endOfVar
+1, '%');
585 if (endOfVar2
!= NULL
) endOfVar
= endOfVar2
;
588 memcpy(thisVar
, start
, ((endOfVar
- start
) + 1) * sizeof(WCHAR
));
589 thisVar
[(endOfVar
- start
)+1] = 0x00;
590 colonpos
= strchrW(thisVar
+1, ':');
592 /* If there's complex substitution, just need %var% for now
593 to get the expanded data to play with */
596 savedchar
= *(colonpos
+1);
597 *(colonpos
+1) = 0x00;
600 WINE_TRACE("Retrieving contents of %s\n", wine_dbgstr_w(thisVar
));
602 /* Expand to contents, if unchanged, return */
603 /* Handle DATE, TIME, ERRORLEVEL and CD replacements allowing */
604 /* override if existing env var called that name */
605 if (WCMD_is_magic_envvar(thisVar
, ErrorLvl
)) {
606 static const WCHAR fmt
[] = {'%','d','\0'};
607 wsprintfW(thisVarContents
, fmt
, errorlevel
);
608 len
= strlenW(thisVarContents
);
609 } else if (WCMD_is_magic_envvar(thisVar
, Date
)) {
610 GetDateFormatW(LOCALE_USER_DEFAULT
, DATE_SHORTDATE
, NULL
,
611 NULL
, thisVarContents
, MAXSTRING
);
612 len
= strlenW(thisVarContents
);
613 } else if (WCMD_is_magic_envvar(thisVar
, Time
)) {
614 GetTimeFormatW(LOCALE_USER_DEFAULT
, TIME_NOSECONDS
, NULL
,
615 NULL
, thisVarContents
, MAXSTRING
);
616 len
= strlenW(thisVarContents
);
617 } else if (WCMD_is_magic_envvar(thisVar
, Cd
)) {
618 GetCurrentDirectoryW(MAXSTRING
, thisVarContents
);
619 len
= strlenW(thisVarContents
);
620 } else if (WCMD_is_magic_envvar(thisVar
, Random
)) {
621 static const WCHAR fmt
[] = {'%','d','\0'};
622 wsprintfW(thisVarContents
, fmt
, rand() % 32768);
623 len
= strlenW(thisVarContents
);
625 /* Look for a matching 'for' variable */
627 (CompareStringW(LOCALE_USER_DEFAULT
,
630 (colonpos
- thisVar
) - 1,
631 forVar
, -1) == CSTR_EQUAL
)) {
632 strcpyW(thisVarContents
, forVal
);
633 len
= strlenW(thisVarContents
);
637 len
= ExpandEnvironmentStringsW(thisVar
, thisVarContents
,
638 sizeof(thisVarContents
)/sizeof(WCHAR
));
644 /* In a batch program, unknown env vars are replaced with nothing,
645 note syntax %garbage:1,3% results in anything after the ':'
647 From the command line, you just get back what you entered */
648 if (lstrcmpiW(thisVar
, thisVarContents
) == 0) {
650 /* Restore the complex part after the compare */
653 *(colonpos
+1) = savedchar
;
656 /* Command line - just ignore this */
657 if (context
== NULL
) return endOfVar
+1;
660 /* Batch - replace unknown env var with nothing */
661 if (colonpos
== NULL
) {
662 WCMD_strsubstW(start
, endOfVar
+ 1, NULL
, 0);
664 len
= strlenW(thisVar
);
665 thisVar
[len
-1] = 0x00;
666 /* If %:...% supplied, : is retained */
667 if (colonpos
== thisVar
+1) {
668 WCMD_strsubstW(start
, endOfVar
+ 1, colonpos
, -1);
670 WCMD_strsubstW(start
, endOfVar
+ 1, colonpos
+ 1, -1);
677 /* See if we need to do complex substitution (any ':'s), if not
678 then our work here is done */
679 if (colonpos
== NULL
) {
680 WCMD_strsubstW(start
, endOfVar
+ 1, thisVarContents
, -1);
684 /* Restore complex bit */
686 *(colonpos
+1) = savedchar
;
689 Handle complex substitutions:
690 xxx=yyy (replace xxx with yyy)
691 *xxx=yyy (replace up to and including xxx with yyy)
692 ~x (from x WCHARs in)
693 ~-x (from x WCHARs from the end)
694 ~x,y (from x WCHARs in for y WCHARacters)
695 ~x,-y (from x WCHARs in until y WCHARacters from the end)
698 /* ~ is substring manipulation */
699 if (savedchar
== '~') {
701 int substrposition
, substrlength
= 0;
702 WCHAR
*commapos
= strchrW(colonpos
+2, ',');
705 substrposition
= atolW(colonpos
+2);
706 if (commapos
) substrlength
= atolW(commapos
+1);
709 if (substrposition
>= 0) {
710 startCopy
= &thisVarContents
[min(substrposition
, len
)];
712 startCopy
= &thisVarContents
[max(0, len
+substrposition
-1)];
715 if (commapos
== NULL
) {
717 WCMD_strsubstW(start
, endOfVar
+ 1, startCopy
, -1);
718 } else if (substrlength
< 0) {
720 int copybytes
= (len
+substrlength
-1)-(startCopy
-thisVarContents
);
721 if (copybytes
> len
) copybytes
= len
;
722 else if (copybytes
< 0) copybytes
= 0;
723 WCMD_strsubstW(start
, endOfVar
+ 1, startCopy
, copybytes
);
725 WCMD_strsubstW(start
, endOfVar
+ 1, startCopy
, substrlength
);
728 /* search and replace manipulation */
730 WCHAR
*equalspos
= strstrW(colonpos
, equalW
);
731 WCHAR
*replacewith
= equalspos
+1;
736 if (equalspos
== NULL
) return start
+1;
737 s
= WCMD_strdupW(endOfVar
+ 1);
739 /* Null terminate both strings */
740 thisVar
[strlenW(thisVar
)-1] = 0x00;
743 /* Since we need to be case insensitive, copy the 2 buffers */
744 searchIn
= WCMD_strdupW(thisVarContents
);
745 CharUpperBuffW(searchIn
, strlenW(thisVarContents
));
746 searchFor
= WCMD_strdupW(colonpos
+1);
747 CharUpperBuffW(searchFor
, strlenW(colonpos
+1));
749 /* Handle wildcard case */
750 if (*(colonpos
+1) == '*') {
751 /* Search for string to replace */
752 found
= strstrW(searchIn
, searchFor
+1);
756 strcpyW(start
, replacewith
);
757 strcatW(start
, thisVarContents
+ (found
-searchIn
) + strlenW(searchFor
+1));
761 strcpyW(start
, thisVarContents
);
766 /* Loop replacing all instances */
767 WCHAR
*lastFound
= searchIn
;
768 WCHAR
*outputposn
= start
;
771 while ((found
= strstrW(lastFound
, searchFor
))) {
772 lstrcpynW(outputposn
,
773 thisVarContents
+ (lastFound
-searchIn
),
774 (found
- lastFound
)+1);
775 outputposn
= outputposn
+ (found
- lastFound
);
776 strcatW(outputposn
, replacewith
);
777 outputposn
= outputposn
+ strlenW(replacewith
);
778 lastFound
= found
+ strlenW(searchFor
);
781 thisVarContents
+ (lastFound
-searchIn
));
782 strcatW(outputposn
, s
);
784 HeapFree(GetProcessHeap(), 0, s
);
785 HeapFree(GetProcessHeap(), 0, searchIn
);
786 HeapFree(GetProcessHeap(), 0, searchFor
);
791 /*****************************************************************************
792 * Expand the command. Native expands lines from batch programs as they are
793 * read in and not again, except for 'for' variable substitution.
794 * eg. As evidence, "echo %1 && shift && echo %1" or "echo %%path%%"
796 static void handleExpansion(WCHAR
*cmd
, BOOL justFors
,
797 const WCHAR
*forVariable
, const WCHAR
*forValue
) {
799 /* For commands in a context (batch program): */
800 /* Expand environment variables in a batch file %{0-9} first */
801 /* including support for any ~ modifiers */
803 /* Expand the DATE, TIME, CD, RANDOM and ERRORLEVEL special */
804 /* names allowing environment variable overrides */
805 /* NOTE: To support the %PATH:xxx% syntax, also perform */
806 /* manual expansion of environment variables here */
812 while ((p
= strchrW(p
, '%'))) {
814 WINE_TRACE("Translate command:%s %d (at: %s)\n",
815 wine_dbgstr_w(cmd
), justFors
, wine_dbgstr_w(p
));
818 /* Don't touch %% unless its in Batch */
819 if (!justFors
&& *(p
+1) == '%') {
821 WCMD_strsubstW(p
, p
+1, NULL
, 0);
825 /* Replace %~ modifications if in batch program */
826 } else if (*(p
+1) == '~') {
827 WCMD_HandleTildaModifiers(&p
, forVariable
, forValue
, justFors
);
830 /* Replace use of %0...%9 if in batch program*/
831 } else if (!justFors
&& context
&& (i
>= 0) && (i
<= 9)) {
832 t
= WCMD_parameter(context
-> command
, i
+ context
-> shift_count
[i
], NULL
, NULL
);
833 WCMD_strsubstW(p
, p
+2, t
, -1);
835 /* Replace use of %* if in batch program*/
836 } else if (!justFors
&& context
&& *(p
+1)=='*') {
837 WCHAR
*startOfParms
= NULL
;
838 WCMD_parameter(context
-> command
, 1, &startOfParms
, NULL
);
839 if (startOfParms
!= NULL
)
840 WCMD_strsubstW(p
, p
+2, startOfParms
, -1);
842 WCMD_strsubstW(p
, p
+2, NULL
, 0);
844 } else if (forVariable
&&
845 (CompareStringW(LOCALE_USER_DEFAULT
,
848 strlenW(forVariable
),
849 forVariable
, -1) == CSTR_EQUAL
)) {
850 WCMD_strsubstW(p
, p
+ strlenW(forVariable
), forValue
, -1);
852 } else if (!justFors
) {
853 p
= WCMD_expand_envvar(p
, forVariable
, forValue
);
855 /* In a FOR loop, see if this is the variable to replace */
856 } else { /* Ignore %'s on second pass of batch program */
865 /*******************************************************************
866 * WCMD_parse - parse a command into parameters and qualifiers.
868 * On exit, all qualifiers are concatenated into q, the first string
869 * not beginning with "/" is in p1 and the
870 * second in p2. Any subsequent non-qualifier strings are lost.
871 * Parameters in quotes are handled.
873 static void WCMD_parse (const WCHAR
*s
, WCHAR
*q
, WCHAR
*p1
, WCHAR
*p2
)
877 *q
= *p1
= *p2
= '\0';
882 while ((*s
!= '\0') && (*s
!= ' ') && *s
!= '/') {
883 *q
++ = toupperW (*s
++);
893 while ((*s
!= '\0') && (*s
!= '"')) {
894 if (p
== 0) *p1
++ = *s
++;
895 else if (p
== 1) *p2
++ = *s
++;
898 if (p
== 0) *p1
= '\0';
899 if (p
== 1) *p2
= '\0';
906 while ((*s
!= '\0') && (*s
!= ' ') && (*s
!= '\t')
907 && (*s
!= '=') && (*s
!= ',') ) {
908 if (p
== 0) *p1
++ = *s
++;
909 else if (p
== 1) *p2
++ = *s
++;
912 /* Skip concurrent parms */
913 while ((*s
== ' ') || (*s
== '\t') || (*s
== '=') || (*s
== ',') ) s
++;
915 if (p
== 0) *p1
= '\0';
916 if (p
== 1) *p2
= '\0';
922 static void init_msvcrt_io_block(STARTUPINFOW
* st
)
925 /* fetch the parent MSVCRT info block if any, so that the child can use the
926 * same handles as its grand-father
928 st_p
.cb
= sizeof(STARTUPINFOW
);
929 GetStartupInfoW(&st_p
);
930 st
->cbReserved2
= st_p
.cbReserved2
;
931 st
->lpReserved2
= st_p
.lpReserved2
;
932 if (st_p
.cbReserved2
&& st_p
.lpReserved2
)
934 /* Override the entries for fd 0,1,2 if we happened
935 * to change those std handles (this depends on the way cmd sets
936 * its new input & output handles)
938 size_t sz
= max(sizeof(unsigned) + (sizeof(char) + sizeof(HANDLE
)) * 3, st_p
.cbReserved2
);
939 BYTE
* ptr
= HeapAlloc(GetProcessHeap(), 0, sz
);
942 unsigned num
= *(unsigned*)st_p
.lpReserved2
;
943 char* flags
= (char*)(ptr
+ sizeof(unsigned));
944 HANDLE
* handles
= (HANDLE
*)(flags
+ num
* sizeof(char));
946 memcpy(ptr
, st_p
.lpReserved2
, st_p
.cbReserved2
);
947 st
->cbReserved2
= sz
;
948 st
->lpReserved2
= ptr
;
950 #define WX_OPEN 0x01 /* see dlls/msvcrt/file.c */
951 if (num
<= 0 || (flags
[0] & WX_OPEN
))
953 handles
[0] = GetStdHandle(STD_INPUT_HANDLE
);
956 if (num
<= 1 || (flags
[1] & WX_OPEN
))
958 handles
[1] = GetStdHandle(STD_OUTPUT_HANDLE
);
961 if (num
<= 2 || (flags
[2] & WX_OPEN
))
963 handles
[2] = GetStdHandle(STD_ERROR_HANDLE
);
971 /******************************************************************************
974 * Execute a command line as an external program. Must allow recursion.
977 * Manual testing under windows shows PATHEXT plays a key part in this,
978 * and the search algorithm and precedence appears to be as follows.
981 * If directory supplied on command, just use that directory
982 * If extension supplied on command, look for that explicit name first
983 * Otherwise, search in each directory on the path
985 * If extension supplied on command, look for that explicit name first
986 * Then look for supplied name .* (even if extension supplied, so
987 * 'garbage.exe' will match 'garbage.exe.cmd')
988 * If any found, cycle through PATHEXT looking for name.exe one by one
990 * Once a match has been found, it is launched - Code currently uses
991 * findexecutable to achieve this which is left untouched.
994 void WCMD_run_program (WCHAR
*command
, int called
) {
996 WCHAR temp
[MAX_PATH
];
997 WCHAR pathtosearch
[MAXSTRING
];
999 WCHAR stemofsearch
[MAX_PATH
]; /* maximum allowed executable name is
1000 MAX_PATH, including null character */
1002 WCHAR pathext
[MAXSTRING
];
1003 BOOL extensionsupplied
= FALSE
;
1004 BOOL launched
= FALSE
;
1006 BOOL assumeInternal
= FALSE
;
1008 static const WCHAR envPath
[] = {'P','A','T','H','\0'};
1009 static const WCHAR envPathExt
[] = {'P','A','T','H','E','X','T','\0'};
1010 static const WCHAR delims
[] = {'/','\\',':','\0'};
1012 /* Quick way to get the filename
1013 * (but handle leading / as part of program name, not qualifier)
1015 for (len
= 0; command
[len
] == '/'; len
++) param1
[len
] = '/';
1016 WCMD_parse (command
+ len
, quals
, param1
+ len
, param2
);
1018 if (!(*param1
) && !(*param2
))
1021 /* Calculate the search path and stem to search for */
1022 if (strpbrkW (param1
, delims
) == NULL
) { /* No explicit path given, search path */
1023 static const WCHAR curDir
[] = {'.',';','\0'};
1024 strcpyW(pathtosearch
, curDir
);
1025 len
= GetEnvironmentVariableW(envPath
, &pathtosearch
[2], (sizeof(pathtosearch
)/sizeof(WCHAR
))-2);
1026 if ((len
== 0) || (len
>= (sizeof(pathtosearch
)/sizeof(WCHAR
)) - 2)) {
1027 static const WCHAR curDir
[] = {'.','\0'};
1028 strcpyW (pathtosearch
, curDir
);
1030 if (strchrW(param1
, '.') != NULL
) extensionsupplied
= TRUE
;
1031 if (strlenW(param1
) >= MAX_PATH
)
1033 WCMD_output_asis_stderr(WCMD_LoadMessage(WCMD_LINETOOLONG
));
1037 strcpyW(stemofsearch
, param1
);
1041 /* Convert eg. ..\fred to include a directory by removing file part */
1042 GetFullPathNameW(param1
, sizeof(pathtosearch
)/sizeof(WCHAR
), pathtosearch
, NULL
);
1043 lastSlash
= strrchrW(pathtosearch
, '\\');
1044 if (lastSlash
&& strchrW(lastSlash
, '.') != NULL
) extensionsupplied
= TRUE
;
1045 strcpyW(stemofsearch
, lastSlash
+1);
1047 /* Reduce pathtosearch to a path with trailing '\' to support c:\a.bat and
1048 c:\windows\a.bat syntax */
1049 if (lastSlash
) *(lastSlash
+ 1) = 0x00;
1052 /* Now extract PATHEXT */
1053 len
= GetEnvironmentVariableW(envPathExt
, pathext
, sizeof(pathext
)/sizeof(WCHAR
));
1054 if ((len
== 0) || (len
>= (sizeof(pathext
)/sizeof(WCHAR
)))) {
1055 static const WCHAR dfltPathExt
[] = {'.','b','a','t',';',
1056 '.','c','o','m',';',
1057 '.','c','m','d',';',
1058 '.','e','x','e','\0'};
1059 strcpyW (pathext
, dfltPathExt
);
1062 /* Loop through the search path, dir by dir */
1063 pathposn
= pathtosearch
;
1064 WINE_TRACE("Searching in '%s' for '%s'\n", wine_dbgstr_w(pathtosearch
),
1065 wine_dbgstr_w(stemofsearch
));
1066 while (!launched
&& pathposn
) {
1068 WCHAR thisDir
[MAX_PATH
] = {'\0'};
1072 /* Work on the first directory on the search path */
1073 pos
= strchrW(pathposn
, ';');
1075 memcpy(thisDir
, pathposn
, (pos
-pathposn
) * sizeof(WCHAR
));
1076 thisDir
[(pos
-pathposn
)] = 0x00;
1080 strcpyW(thisDir
, pathposn
);
1084 /* Since you can have eg. ..\.. on the path, need to expand
1085 to full information */
1086 strcpyW(temp
, thisDir
);
1087 GetFullPathNameW(temp
, MAX_PATH
, thisDir
, NULL
);
1089 /* 1. If extension supplied, see if that file exists */
1090 strcatW(thisDir
, slashW
);
1091 strcatW(thisDir
, stemofsearch
);
1092 pos
= &thisDir
[strlenW(thisDir
)]; /* Pos = end of name */
1094 /* 1. If extension supplied, see if that file exists */
1095 if (extensionsupplied
) {
1096 if (GetFileAttributesW(thisDir
) != INVALID_FILE_ATTRIBUTES
) {
1101 /* 2. Any .* matches? */
1104 WIN32_FIND_DATAW finddata
;
1105 static const WCHAR allFiles
[] = {'.','*','\0'};
1107 strcatW(thisDir
,allFiles
);
1108 h
= FindFirstFileW(thisDir
, &finddata
);
1110 if (h
!= INVALID_HANDLE_VALUE
) {
1112 WCHAR
*thisExt
= pathext
;
1114 /* 3. Yes - Try each path ext */
1116 WCHAR
*nextExt
= strchrW(thisExt
, ';');
1119 memcpy(pos
, thisExt
, (nextExt
-thisExt
) * sizeof(WCHAR
));
1120 pos
[(nextExt
-thisExt
)] = 0x00;
1121 thisExt
= nextExt
+1;
1123 strcpyW(pos
, thisExt
);
1127 if (GetFileAttributesW(thisDir
) != INVALID_FILE_ATTRIBUTES
) {
1135 /* Internal programs won't be picked up by this search, so even
1136 though not found, try one last createprocess and wait for it
1138 Note: Ideally we could tell between a console app (wait) and a
1139 windows app, but the API's for it fail in this case */
1140 if (!found
&& pathposn
== NULL
) {
1141 WINE_TRACE("ASSUMING INTERNAL\n");
1142 assumeInternal
= TRUE
;
1144 WINE_TRACE("Found as %s\n", wine_dbgstr_w(thisDir
));
1147 /* Once found, launch it */
1148 if (found
|| assumeInternal
) {
1150 PROCESS_INFORMATION pe
;
1154 WCHAR
*ext
= strrchrW( thisDir
, '.' );
1155 static const WCHAR batExt
[] = {'.','b','a','t','\0'};
1156 static const WCHAR cmdExt
[] = {'.','c','m','d','\0'};
1160 /* Special case BAT and CMD */
1161 if (ext
&& (!strcmpiW(ext
, batExt
) || !strcmpiW(ext
, cmdExt
))) {
1162 WCMD_batch (thisDir
, command
, called
, NULL
, INVALID_HANDLE_VALUE
);
1166 /* thisDir contains the file to be launched, but with what?
1167 eg. a.exe will require a.exe to be launched, a.html may be iexplore */
1168 hinst
= FindExecutableW (thisDir
, NULL
, temp
);
1169 if ((INT_PTR
)hinst
< 32)
1172 console
= SHGetFileInfoW(temp
, 0, &psfi
, sizeof(psfi
), SHGFI_EXETYPE
);
1174 ZeroMemory (&st
, sizeof(STARTUPINFOW
));
1175 st
.cb
= sizeof(STARTUPINFOW
);
1176 init_msvcrt_io_block(&st
);
1178 /* Launch the process and if a CUI wait on it to complete
1179 Note: Launching internal wine processes cannot specify a full path to exe */
1180 status
= CreateProcessW(assumeInternal
?NULL
: thisDir
,
1181 command
, NULL
, NULL
, TRUE
, 0, NULL
, NULL
, &st
, &pe
);
1182 if ((opt_c
|| opt_k
) && !opt_s
&& !status
1183 && GetLastError()==ERROR_FILE_NOT_FOUND
&& command
[0]=='\"') {
1184 /* strip first and last quote WCHARacters and try again */
1185 WCMD_strip_quotes(command
);
1187 WCMD_run_program(command
, called
);
1194 if (!assumeInternal
&& !console
) errorlevel
= 0;
1197 /* Always wait when called in a batch program context */
1198 if (assumeInternal
|| context
|| !HIWORD(console
)) WaitForSingleObject (pe
.hProcess
, INFINITE
);
1199 GetExitCodeProcess (pe
.hProcess
, &errorlevel
);
1200 if (errorlevel
== STILL_ACTIVE
) errorlevel
= 0;
1202 CloseHandle(pe
.hProcess
);
1203 CloseHandle(pe
.hThread
);
1209 /* Not found anywhere - give up */
1210 SetLastError(ERROR_FILE_NOT_FOUND
);
1211 WCMD_print_error ();
1213 /* If a command fails to launch, it sets errorlevel 9009 - which
1214 does not seem to have any associated constant definition */
1220 /*****************************************************************************
1221 * Process one command. If the command is EXIT this routine does not return.
1222 * We will recurse through here executing batch files.
1224 void WCMD_execute (const WCHAR
*command
, const WCHAR
*redirects
,
1225 const WCHAR
*forVariable
, const WCHAR
*forValue
,
1228 WCHAR
*cmd
, *p
, *redir
;
1230 DWORD count
, creationDisposition
;
1233 SECURITY_ATTRIBUTES sa
;
1234 WCHAR
*new_cmd
= NULL
;
1235 WCHAR
*new_redir
= NULL
;
1236 HANDLE old_stdhandles
[3] = {GetStdHandle (STD_INPUT_HANDLE
),
1237 GetStdHandle (STD_OUTPUT_HANDLE
),
1238 GetStdHandle (STD_ERROR_HANDLE
)};
1239 DWORD idx_stdhandles
[3] = {STD_INPUT_HANDLE
,
1242 BOOL prev_echo_mode
, piped
= FALSE
;
1244 WINE_TRACE("command on entry:%s (%p), with forVariable '%s'='%s'\n",
1245 wine_dbgstr_w(command
), cmdList
,
1246 wine_dbgstr_w(forVariable
), wine_dbgstr_w(forValue
));
1248 /* If the next command is a pipe then we implement pipes by redirecting
1249 the output from this command to a temp file and input into the
1250 next command from that temp file.
1251 FIXME: Use of named pipes would make more sense here as currently this
1252 process has to finish before the next one can start but this requires
1253 a change to not wait for the first app to finish but rather the pipe */
1254 if (cmdList
&& (*cmdList
)->nextcommand
&&
1255 (*cmdList
)->nextcommand
->prevDelim
== CMD_PIPE
) {
1257 WCHAR temp_path
[MAX_PATH
];
1258 static const WCHAR cmdW
[] = {'C','M','D','\0'};
1260 /* Remember piping is in action */
1261 WINE_TRACE("Output needs to be piped\n");
1264 /* Generate a unique temporary filename */
1265 GetTempPathW(sizeof(temp_path
)/sizeof(WCHAR
), temp_path
);
1266 GetTempFileNameW(temp_path
, cmdW
, 0, (*cmdList
)->nextcommand
->pipeFile
);
1267 WINE_TRACE("Using temporary file of %s\n",
1268 wine_dbgstr_w((*cmdList
)->nextcommand
->pipeFile
));
1271 /* Move copy of the command onto the heap so it can be expanded */
1272 new_cmd
= HeapAlloc( GetProcessHeap(), 0, MAXSTRING
* sizeof(WCHAR
));
1275 WINE_ERR("Could not allocate memory for new_cmd\n");
1278 strcpyW(new_cmd
, command
);
1280 /* Move copy of the redirects onto the heap so it can be expanded */
1281 new_redir
= HeapAlloc( GetProcessHeap(), 0, MAXSTRING
* sizeof(WCHAR
));
1284 WINE_ERR("Could not allocate memory for new_redir\n");
1285 HeapFree( GetProcessHeap(), 0, new_cmd
);
1289 /* If piped output, send stdout to the pipe by appending >filename to redirects */
1291 static const WCHAR redirOut
[] = {'%','s',' ','>',' ','%','s','\0'};
1292 wsprintfW (new_redir
, redirOut
, redirects
, (*cmdList
)->nextcommand
->pipeFile
);
1293 WINE_TRACE("Redirects now %s\n", wine_dbgstr_w(new_redir
));
1295 strcpyW(new_redir
, redirects
);
1298 /* Expand variables in command line mode only (batch mode will
1299 be expanded as the line is read in, except for 'for' loops) */
1300 handleExpansion(new_cmd
, (context
!= NULL
), forVariable
, forValue
);
1301 handleExpansion(new_redir
, (context
!= NULL
), forVariable
, forValue
);
1305 * Changing default drive has to be handled as a special case.
1308 if ((cmd
[1] == ':') && IsCharAlphaW(cmd
[0]) && (strlenW(cmd
) == 2)) {
1310 WCHAR dir
[MAX_PATH
];
1312 /* According to MSDN CreateProcess docs, special env vars record
1313 the current directory on each drive, in the form =C:
1314 so see if one specified, and if so go back to it */
1315 strcpyW(envvar
, equalW
);
1316 strcatW(envvar
, cmd
);
1317 if (GetEnvironmentVariableW(envvar
, dir
, MAX_PATH
) == 0) {
1318 static const WCHAR fmt
[] = {'%','s','\\','\0'};
1319 wsprintfW(cmd
, fmt
, cmd
);
1320 WINE_TRACE("No special directory settings, using dir of %s\n", wine_dbgstr_w(cmd
));
1322 WINE_TRACE("Got directory %s as %s\n", wine_dbgstr_w(envvar
), wine_dbgstr_w(cmd
));
1323 status
= SetCurrentDirectoryW(cmd
);
1324 if (!status
) WCMD_print_error ();
1325 HeapFree( GetProcessHeap(), 0, cmd
);
1326 HeapFree( GetProcessHeap(), 0, new_redir
);
1330 sa
.nLength
= sizeof(sa
);
1331 sa
.lpSecurityDescriptor
= NULL
;
1332 sa
.bInheritHandle
= TRUE
;
1335 * Redirect stdin, stdout and/or stderr if required.
1338 /* STDIN could come from a preceding pipe, so delete on close if it does */
1339 if (cmdList
&& (*cmdList
)->pipeFile
[0] != 0x00) {
1340 WINE_TRACE("Input coming from %s\n", wine_dbgstr_w((*cmdList
)->pipeFile
));
1341 h
= CreateFileW((*cmdList
)->pipeFile
, GENERIC_READ
,
1342 FILE_SHARE_READ
, &sa
, OPEN_EXISTING
,
1343 FILE_ATTRIBUTE_NORMAL
| FILE_FLAG_DELETE_ON_CLOSE
, NULL
);
1344 if (h
== INVALID_HANDLE_VALUE
) {
1345 WCMD_print_error ();
1346 HeapFree( GetProcessHeap(), 0, cmd
);
1347 HeapFree( GetProcessHeap(), 0, new_redir
);
1350 SetStdHandle (STD_INPUT_HANDLE
, h
);
1352 /* No need to remember the temporary name any longer once opened */
1353 (*cmdList
)->pipeFile
[0] = 0x00;
1355 /* Otherwise STDIN could come from a '<' redirect */
1356 } else if ((p
= strchrW(new_redir
,'<')) != NULL
) {
1357 h
= CreateFileW(WCMD_parameter(++p
, 0, NULL
, NULL
), GENERIC_READ
, FILE_SHARE_READ
,
1358 &sa
, OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, NULL
);
1359 if (h
== INVALID_HANDLE_VALUE
) {
1360 WCMD_print_error ();
1361 HeapFree( GetProcessHeap(), 0, cmd
);
1362 HeapFree( GetProcessHeap(), 0, new_redir
);
1365 SetStdHandle (STD_INPUT_HANDLE
, h
);
1368 /* Scan the whole command looking for > and 2> */
1370 while (redir
!= NULL
&& ((p
= strchrW(redir
,'>')) != NULL
)) {
1373 if (p
> redir
&& (*(p
-1)=='2'))
1380 creationDisposition
= OPEN_ALWAYS
;
1384 creationDisposition
= CREATE_ALWAYS
;
1387 /* Add support for 2>&1 */
1390 int idx
= *(p
+1) - '0';
1392 if (DuplicateHandle(GetCurrentProcess(),
1393 GetStdHandle(idx_stdhandles
[idx
]),
1394 GetCurrentProcess(),
1396 0, TRUE
, DUPLICATE_SAME_ACCESS
) == 0) {
1397 WINE_FIXME("Duplicating handle failed with gle %d\n", GetLastError());
1399 WINE_TRACE("Redirect %d (%p) to %d (%p)\n", handle
, GetStdHandle(idx_stdhandles
[idx
]), idx
, h
);
1402 WCHAR
*param
= WCMD_parameter(p
, 0, NULL
, NULL
);
1403 h
= CreateFileW(param
, GENERIC_WRITE
, 0, &sa
, creationDisposition
,
1404 FILE_ATTRIBUTE_NORMAL
, NULL
);
1405 if (h
== INVALID_HANDLE_VALUE
) {
1406 WCMD_print_error ();
1407 HeapFree( GetProcessHeap(), 0, cmd
);
1408 HeapFree( GetProcessHeap(), 0, new_redir
);
1411 if (SetFilePointer (h
, 0, NULL
, FILE_END
) ==
1412 INVALID_SET_FILE_POINTER
) {
1413 WCMD_print_error ();
1415 WINE_TRACE("Redirect %d to '%s' (%p)\n", handle
, wine_dbgstr_w(param
), h
);
1418 SetStdHandle (idx_stdhandles
[handle
], h
);
1422 * Strip leading whitespaces, and a '@' if supplied
1424 whichcmd
= WCMD_skip_leading_spaces(cmd
);
1425 WINE_TRACE("Command: '%s'\n", wine_dbgstr_w(cmd
));
1426 if (whichcmd
[0] == '@') whichcmd
++;
1429 * Check if the command entered is internal. If it is, pass the rest of the
1430 * line down to the command. If not try to run a program.
1434 while (IsCharAlphaNumericW(whichcmd
[count
])) {
1437 for (i
=0; i
<=WCMD_EXIT
; i
++) {
1438 if (CompareStringW(LOCALE_USER_DEFAULT
, NORM_IGNORECASE
| SORT_STRINGSORT
,
1439 whichcmd
, count
, inbuilt
[i
], -1) == CSTR_EQUAL
) break;
1441 p
= WCMD_skip_leading_spaces (&whichcmd
[count
]);
1442 WCMD_parse (p
, quals
, param1
, param2
);
1443 WINE_TRACE("param1: %s, param2: %s\n", wine_dbgstr_w(param1
), wine_dbgstr_w(param2
));
1445 if (i
<= WCMD_EXIT
&& (p
[0] == '/') && (p
[1] == '?')) {
1446 /* this is a help request for a builtin program */
1448 memcpy(p
, whichcmd
, count
* sizeof(WCHAR
));
1460 WCMD_setshow_default (p
);
1463 WCMD_clear_screen ();
1472 WCMD_setshow_date ();
1482 WCMD_echo(&whichcmd
[count
]);
1485 WCMD_for (p
, cmdList
);
1488 WCMD_goto (cmdList
);
1494 WCMD_if (p
, cmdList
);
1497 WCMD_volume (TRUE
, p
);
1501 WCMD_create_dir (p
);
1507 WCMD_setshow_path (p
);
1513 WCMD_setshow_prompt ();
1523 WCMD_remove_dir (p
);
1532 WCMD_setshow_env (p
);
1538 WCMD_setshow_time ();
1541 if (strlenW(&whichcmd
[count
]) > 0)
1542 WCMD_title(&whichcmd
[count
+1]);
1548 WCMD_output_asis(newline
);
1555 WCMD_volume (FALSE
, p
);
1564 WCMD_assoc(p
, TRUE
);
1570 WCMD_assoc(p
, FALSE
);
1579 WCMD_exit (cmdList
);
1582 prev_echo_mode
= echo_mode
;
1583 WCMD_run_program (whichcmd
, 0);
1584 echo_mode
= prev_echo_mode
;
1586 HeapFree( GetProcessHeap(), 0, cmd
);
1587 HeapFree( GetProcessHeap(), 0, new_redir
);
1589 /* Restore old handles */
1590 for (i
=0; i
<3; i
++) {
1591 if (old_stdhandles
[i
] != GetStdHandle(idx_stdhandles
[i
])) {
1592 CloseHandle (GetStdHandle (idx_stdhandles
[i
]));
1593 SetStdHandle (idx_stdhandles
[i
], old_stdhandles
[i
]);
1598 /*************************************************************************
1600 * Load a string from the resource file, handling any error
1601 * Returns string retrieved from resource file
1603 WCHAR
*WCMD_LoadMessage(UINT id
) {
1604 static WCHAR msg
[2048];
1605 static const WCHAR failedMsg
[] = {'F','a','i','l','e','d','!','\0'};
1607 if (!LoadStringW(GetModuleHandleW(NULL
), id
, msg
, sizeof(msg
)/sizeof(WCHAR
))) {
1608 WINE_FIXME("LoadString failed with %d\n", GetLastError());
1609 strcpyW(msg
, failedMsg
);
1614 /***************************************************************************
1617 * Dumps out the parsed command line to ensure syntax is correct
1619 static void WCMD_DumpCommands(CMD_LIST
*commands
) {
1620 CMD_LIST
*thisCmd
= commands
;
1622 WINE_TRACE("Parsed line:\n");
1623 while (thisCmd
!= NULL
) {
1624 WINE_TRACE("%p %d %2.2d %p %s Redir:%s\n",
1627 thisCmd
->bracketDepth
,
1628 thisCmd
->nextcommand
,
1629 wine_dbgstr_w(thisCmd
->command
),
1630 wine_dbgstr_w(thisCmd
->redirects
));
1631 thisCmd
= thisCmd
->nextcommand
;
1635 /***************************************************************************
1638 * Adds a command to the current command list
1640 static void WCMD_addCommand(WCHAR
*command
, int *commandLen
,
1641 WCHAR
*redirs
, int *redirLen
,
1642 WCHAR
**copyTo
, int **copyToLen
,
1643 CMD_DELIMITERS prevDelim
, int curDepth
,
1644 CMD_LIST
**lastEntry
, CMD_LIST
**output
) {
1646 CMD_LIST
*thisEntry
= NULL
;
1648 /* Allocate storage for command */
1649 thisEntry
= HeapAlloc(GetProcessHeap(), 0, sizeof(CMD_LIST
));
1651 /* Copy in the command */
1653 thisEntry
->command
= HeapAlloc(GetProcessHeap(), 0,
1654 (*commandLen
+1) * sizeof(WCHAR
));
1655 memcpy(thisEntry
->command
, command
, *commandLen
* sizeof(WCHAR
));
1656 thisEntry
->command
[*commandLen
] = 0x00;
1658 /* Copy in the redirects */
1659 thisEntry
->redirects
= HeapAlloc(GetProcessHeap(), 0,
1660 (*redirLen
+1) * sizeof(WCHAR
));
1661 memcpy(thisEntry
->redirects
, redirs
, *redirLen
* sizeof(WCHAR
));
1662 thisEntry
->redirects
[*redirLen
] = 0x00;
1663 thisEntry
->pipeFile
[0] = 0x00;
1665 /* Reset the lengths */
1668 *copyToLen
= commandLen
;
1672 thisEntry
->command
= NULL
;
1673 thisEntry
->redirects
= NULL
;
1674 thisEntry
->pipeFile
[0] = 0x00;
1677 /* Fill in other fields */
1678 thisEntry
->nextcommand
= NULL
;
1679 thisEntry
->prevDelim
= prevDelim
;
1680 thisEntry
->bracketDepth
= curDepth
;
1682 (*lastEntry
)->nextcommand
= thisEntry
;
1684 *output
= thisEntry
;
1686 *lastEntry
= thisEntry
;
1690 /***************************************************************************
1693 * Checks if the quote pointed to is the end-quote.
1697 * 1) The current parameter ends at EOL or at the beginning
1698 * of a redirection or pipe and not in a quote section.
1700 * 2) If the next character is a space and not in a quote section.
1702 * Returns TRUE if this is an end quote, and FALSE if it is not.
1705 static BOOL
WCMD_IsEndQuote(const WCHAR
*quote
, int quoteIndex
)
1707 int quoteCount
= quoteIndex
;
1710 /* If we are not in a quoted section, then we are not an end-quote */
1716 /* Check how many quotes are left for this parameter */
1717 for(i
=0;quote
[i
];i
++)
1724 /* Quote counting ends at EOL, redirection, space or pipe if current quote is complete */
1725 else if(((quoteCount
% 2) == 0)
1726 && ((quote
[i
] == '<') || (quote
[i
] == '>') || (quote
[i
] == '|') || (quote
[i
] == ' ')))
1732 /* If the quote is part of the last part of a series of quotes-on-quotes, then it must
1734 if(quoteIndex
>= (quoteCount
/ 2))
1743 /***************************************************************************
1744 * WCMD_ReadAndParseLine
1746 * Either uses supplied input or
1747 * Reads a file from the handle, and then...
1748 * Parse the text buffer, splitting into separate commands
1749 * - unquoted && strings split 2 commands but the 2nd is flagged as
1751 * - ( as the first character just ups the bracket depth
1752 * - unquoted ) when bracket depth > 0 terminates a bracket and
1753 * adds a CMD_LIST structure with null command
1754 * - Anything else gets put into the command string (including
1757 WCHAR
*WCMD_ReadAndParseLine(const WCHAR
*optionalcmd
, CMD_LIST
**output
, HANDLE readFrom
)
1761 WCHAR curString
[MAXSTRING
];
1762 int curStringLen
= 0;
1763 WCHAR curRedirs
[MAXSTRING
];
1764 int curRedirsLen
= 0;
1768 CMD_LIST
*lastEntry
= NULL
;
1769 CMD_DELIMITERS prevDelim
= CMD_NONE
;
1770 static WCHAR
*extraSpace
= NULL
; /* Deliberately never freed */
1771 static const WCHAR remCmd
[] = {'r','e','m'};
1772 static const WCHAR forCmd
[] = {'f','o','r'};
1773 static const WCHAR ifCmd
[] = {'i','f'};
1774 static const WCHAR ifElse
[] = {'e','l','s','e'};
1780 BOOL onlyWhiteSpace
= FALSE
;
1781 BOOL lastWasWhiteSpace
= FALSE
;
1782 BOOL lastWasDo
= FALSE
;
1783 BOOL lastWasIn
= FALSE
;
1784 BOOL lastWasElse
= FALSE
;
1785 BOOL lastWasRedirect
= TRUE
;
1787 /* Allocate working space for a command read from keyboard, file etc */
1789 extraSpace
= HeapAlloc(GetProcessHeap(), 0, (MAXSTRING
+1) * sizeof(WCHAR
));
1792 WINE_ERR("Could not allocate memory for extraSpace\n");
1796 /* If initial command read in, use that, otherwise get input from handle */
1797 if (optionalcmd
!= NULL
) {
1798 strcpyW(extraSpace
, optionalcmd
);
1799 } else if (readFrom
== INVALID_HANDLE_VALUE
) {
1800 WINE_FIXME("No command nor handle supplied\n");
1802 if (!WCMD_fgets(extraSpace
, MAXSTRING
, readFrom
))
1805 curPos
= extraSpace
;
1807 /* Handle truncated input - issue warning */
1808 if (strlenW(extraSpace
) == MAXSTRING
-1) {
1809 WCMD_output_asis_stderr(WCMD_LoadMessage(WCMD_TRUNCATEDLINE
));
1810 WCMD_output_asis_stderr(extraSpace
);
1811 WCMD_output_asis_stderr(newline
);
1814 /* Replace env vars if in a batch context */
1815 if (context
) handleExpansion(extraSpace
, FALSE
, NULL
, NULL
);
1816 /* Show prompt before batch line IF echo is on and in batch program */
1817 if (context
&& echo_mode
&& extraSpace
[0] && (extraSpace
[0] != '@')) {
1818 static const WCHAR echoDot
[] = {'e','c','h','o','.'};
1819 static const WCHAR echoCol
[] = {'e','c','h','o',':'};
1820 const DWORD len
= sizeof(echoDot
)/sizeof(echoDot
[0]);
1821 DWORD curr_size
= strlenW(extraSpace
);
1822 DWORD min_len
= (curr_size
< len
? curr_size
: len
);
1824 WCMD_output_asis(extraSpace
);
1825 /* I don't know why Windows puts a space here but it does */
1826 /* Except for lines starting with 'echo.' or 'echo:'. Ask MS why */
1827 if (CompareStringW(LOCALE_SYSTEM_DEFAULT
, NORM_IGNORECASE
,
1828 extraSpace
, min_len
, echoDot
, len
) != CSTR_EQUAL
1829 && CompareStringW(LOCALE_SYSTEM_DEFAULT
, NORM_IGNORECASE
,
1830 extraSpace
, min_len
, echoCol
, len
) != CSTR_EQUAL
)
1832 WCMD_output_asis(space
);
1834 WCMD_output_asis(newline
);
1837 /* Start with an empty string, copying to the command string */
1840 curCopyTo
= curString
;
1841 curLen
= &curStringLen
;
1842 lastWasRedirect
= FALSE
; /* Required for eg spaces between > and filename */
1844 /* Parse every character on the line being processed */
1845 while (*curPos
!= 0x00) {
1850 WINE_TRACE("Looking at '%c' (len:%d, lws:%d, ows:%d)\n", *curPos, *curLen,
1851 lastWasWhiteSpace, onlyWhiteSpace);
1854 /* Certain commands need special handling */
1855 if (curStringLen
== 0 && curCopyTo
== curString
) {
1856 static const WCHAR forDO
[] = {'d','o'};
1858 /* If command starts with 'rem ', ignore any &&, ( etc. */
1859 if (WCMD_keyword_ws_found(remCmd
, sizeof(remCmd
)/sizeof(remCmd
[0]), curPos
)) {
1862 } else if (WCMD_keyword_ws_found(forCmd
, sizeof(forCmd
)/sizeof(forCmd
[0]), curPos
)) {
1865 /* If command starts with 'if ' or 'else ', handle ('s mid line. We should ensure this
1866 is only true in the command portion of the IF statement, but this
1867 should suffice for now
1868 FIXME: Silly syntax like "if 1(==1( (
1870 )" will be parsed wrong */
1871 } else if (WCMD_keyword_ws_found(ifCmd
, sizeof(ifCmd
)/sizeof(ifCmd
[0]), curPos
)) {
1874 } else if (WCMD_keyword_ws_found(ifElse
, sizeof(ifElse
)/sizeof(ifElse
[0]), curPos
)) {
1875 const int keyw_len
= sizeof(ifElse
)/sizeof(ifElse
[0]) + 1;
1878 onlyWhiteSpace
= TRUE
;
1879 memcpy(&curCopyTo
[*curLen
], curPos
, keyw_len
*sizeof(WCHAR
));
1880 (*curLen
)+=keyw_len
;
1884 /* In a for loop, the DO command will follow a close bracket followed by
1885 whitespace, followed by DO, ie closeBracket inserts a NULL entry, curLen
1886 is then 0, and all whitespace is skipped */
1888 WCMD_keyword_ws_found(forDO
, sizeof(forDO
)/sizeof(forDO
[0]), curPos
)) {
1889 const int keyw_len
= sizeof(forDO
)/sizeof(forDO
[0]) + 1;
1890 WINE_TRACE("Found 'DO '\n");
1892 onlyWhiteSpace
= TRUE
;
1893 memcpy(&curCopyTo
[*curLen
], curPos
, keyw_len
*sizeof(WCHAR
));
1894 (*curLen
)+=keyw_len
;
1898 } else if (curCopyTo
== curString
) {
1900 /* Special handling for the 'FOR' command */
1901 if (inFor
&& lastWasWhiteSpace
) {
1902 static const WCHAR forIN
[] = {'i','n'};
1904 WINE_TRACE("Found 'FOR ', comparing next parm: '%s'\n", wine_dbgstr_w(curPos
));
1906 if (WCMD_keyword_ws_found(forIN
, sizeof(forIN
)/sizeof(forIN
[0]), curPos
)) {
1907 const int keyw_len
= sizeof(forIN
)/sizeof(forIN
[0]) + 1;
1908 WINE_TRACE("Found 'IN '\n");
1910 onlyWhiteSpace
= TRUE
;
1911 memcpy(&curCopyTo
[*curLen
], curPos
, keyw_len
*sizeof(WCHAR
));
1912 (*curLen
)+=keyw_len
;
1919 /* Nothing 'ends' a REM statement and &&, quotes etc are ineffective,
1920 so just use the default processing ie skip character specific
1922 if (!inRem
) thisChar
= *curPos
;
1923 else thisChar
= 'X'; /* Character with no special processing */
1925 lastWasWhiteSpace
= FALSE
; /* Will be reset below */
1929 case '=': /* drop through - ignore token delimiters at the start of a command */
1930 case ',': /* drop through - ignore token delimiters at the start of a command */
1931 case '\t':/* drop through - ignore token delimiters at the start of a command */
1933 /* If a redirect in place, it ends here */
1934 if (!inQuotes
&& !lastWasRedirect
) {
1936 /* If finishing off a redirect, add a whitespace delimiter */
1937 if (curCopyTo
== curRedirs
) {
1938 curCopyTo
[(*curLen
)++] = ' ';
1940 curCopyTo
= curString
;
1941 curLen
= &curStringLen
;
1944 curCopyTo
[(*curLen
)++] = *curPos
;
1947 /* Remember just processed whitespace */
1948 lastWasWhiteSpace
= TRUE
;
1952 case '>': /* drop through - handle redirect chars the same */
1954 /* Make a redirect start here */
1956 curCopyTo
= curRedirs
;
1957 curLen
= &curRedirsLen
;
1958 lastWasRedirect
= TRUE
;
1961 /* See if 1>, 2> etc, in which case we have some patching up
1962 to do (provided there's a preceding whitespace, and enough
1963 chars read so far) */
1964 if (curStringLen
> 2
1965 && (*(curPos
-1)>='1') && (*(curPos
-1)<='9')
1966 && ((*(curPos
-2)==' ') || (*(curPos
-2)=='\t'))) {
1968 curString
[curStringLen
] = 0x00;
1969 curCopyTo
[(*curLen
)++] = *(curPos
-1);
1972 curCopyTo
[(*curLen
)++] = *curPos
;
1974 /* If a redirect is immediately followed by '&' (ie. 2>&1) then
1975 do not process that ampersand as an AND operator */
1976 if (thisChar
== '>' && *(curPos
+1) == '&') {
1977 curCopyTo
[(*curLen
)++] = *(curPos
+1);
1982 case '|': /* Pipe character only if not || */
1984 lastWasRedirect
= FALSE
;
1986 /* Add an entry to the command list */
1987 if (curStringLen
> 0) {
1989 /* Add the current command */
1990 WCMD_addCommand(curString
, &curStringLen
,
1991 curRedirs
, &curRedirsLen
,
1992 &curCopyTo
, &curLen
,
1993 prevDelim
, curDepth
,
1994 &lastEntry
, output
);
1998 if (*(curPos
+1) == '|') {
1999 curPos
++; /* Skip other | */
2000 prevDelim
= CMD_ONFAILURE
;
2002 prevDelim
= CMD_PIPE
;
2005 curCopyTo
[(*curLen
)++] = *curPos
;
2009 case '"': if (WCMD_IsEndQuote(curPos
, inQuotes
)) {
2012 inQuotes
++; /* Quotes within quotes are fun! */
2014 curCopyTo
[(*curLen
)++] = *curPos
;
2015 lastWasRedirect
= FALSE
;
2018 case '(': /* If a '(' is the first non whitespace in a command portion
2019 ie start of line or just after &&, then we read until an
2020 unquoted ) is found */
2021 WINE_TRACE("Found '(' conditions: curLen(%d), inQ(%d), onlyWS(%d)"
2022 ", for(%d, In:%d, Do:%d)"
2023 ", if(%d, else:%d, lwe:%d)\n",
2026 inFor
, lastWasIn
, lastWasDo
,
2027 inIf
, inElse
, lastWasElse
);
2028 lastWasRedirect
= FALSE
;
2030 /* Ignore open brackets inside the for set */
2031 if (*curLen
== 0 && !inIn
) {
2034 /* If in quotes, ignore brackets */
2035 } else if (inQuotes
) {
2036 curCopyTo
[(*curLen
)++] = *curPos
;
2038 /* In a FOR loop, an unquoted '(' may occur straight after
2040 In an IF statement just handle it regardless as we don't
2042 In an ELSE statement, only allow it straight away after
2043 the ELSE and whitespace
2046 (inElse
&& lastWasElse
&& onlyWhiteSpace
) ||
2047 (inFor
&& (lastWasIn
|| lastWasDo
) && onlyWhiteSpace
)) {
2049 /* If entering into an 'IN', set inIn */
2050 if (inFor
&& lastWasIn
&& onlyWhiteSpace
) {
2051 WINE_TRACE("Inside an IN\n");
2055 /* Add the current command */
2056 WCMD_addCommand(curString
, &curStringLen
,
2057 curRedirs
, &curRedirsLen
,
2058 &curCopyTo
, &curLen
,
2059 prevDelim
, curDepth
,
2060 &lastEntry
, output
);
2064 curCopyTo
[(*curLen
)++] = *curPos
;
2068 case '&': if (!inQuotes
) {
2069 lastWasRedirect
= FALSE
;
2071 /* Add an entry to the command list */
2072 if (curStringLen
> 0) {
2074 /* Add the current command */
2075 WCMD_addCommand(curString
, &curStringLen
,
2076 curRedirs
, &curRedirsLen
,
2077 &curCopyTo
, &curLen
,
2078 prevDelim
, curDepth
,
2079 &lastEntry
, output
);
2083 if (*(curPos
+1) == '&') {
2084 curPos
++; /* Skip other & */
2085 prevDelim
= CMD_ONSUCCESS
;
2087 prevDelim
= CMD_NONE
;
2090 curCopyTo
[(*curLen
)++] = *curPos
;
2094 case ')': if (!inQuotes
&& curDepth
> 0) {
2095 lastWasRedirect
= FALSE
;
2097 /* Add the current command if there is one */
2100 /* Add the current command */
2101 WCMD_addCommand(curString
, &curStringLen
,
2102 curRedirs
, &curRedirsLen
,
2103 &curCopyTo
, &curLen
,
2104 prevDelim
, curDepth
,
2105 &lastEntry
, output
);
2108 /* Add an empty entry to the command list */
2109 prevDelim
= CMD_NONE
;
2110 WCMD_addCommand(NULL
, &curStringLen
,
2111 curRedirs
, &curRedirsLen
,
2112 &curCopyTo
, &curLen
,
2113 prevDelim
, curDepth
,
2114 &lastEntry
, output
);
2117 /* Leave inIn if necessary */
2118 if (inIn
) inIn
= FALSE
;
2120 curCopyTo
[(*curLen
)++] = *curPos
;
2124 lastWasRedirect
= FALSE
;
2125 curCopyTo
[(*curLen
)++] = *curPos
;
2130 /* At various times we need to know if we have only skipped whitespace,
2131 so reset this variable and then it will remain true until a non
2132 whitespace is found */
2133 if ((thisChar
!= ' ') && (thisChar
!= '\t') && (thisChar
!= '\n'))
2134 onlyWhiteSpace
= FALSE
;
2136 /* Flag end of interest in FOR DO and IN parms once something has been processed */
2137 if (!lastWasWhiteSpace
) {
2138 lastWasIn
= lastWasDo
= FALSE
;
2141 /* If we have reached the end, add this command into the list */
2142 if (*curPos
== 0x00 && *curLen
> 0) {
2144 /* Add an entry to the command list */
2145 WCMD_addCommand(curString
, &curStringLen
,
2146 curRedirs
, &curRedirsLen
,
2147 &curCopyTo
, &curLen
,
2148 prevDelim
, curDepth
,
2149 &lastEntry
, output
);
2152 /* If we have reached the end of the string, see if bracketing outstanding */
2153 if (*curPos
== 0x00 && curDepth
> 0 && readFrom
!= INVALID_HANDLE_VALUE
) {
2155 prevDelim
= CMD_NONE
;
2157 memset(extraSpace
, 0x00, (MAXSTRING
+1) * sizeof(WCHAR
));
2159 /* Read more, skipping any blank lines */
2160 while (*extraSpace
== 0x00) {
2161 if (!context
) WCMD_output_asis( WCMD_LoadMessage(WCMD_MOREPROMPT
));
2162 if (!WCMD_fgets(extraSpace
, MAXSTRING
, readFrom
))
2165 curPos
= extraSpace
;
2166 if (context
) handleExpansion(extraSpace
, FALSE
, NULL
, NULL
);
2167 /* Continue to echo commands IF echo is on and in batch program */
2168 if (context
&& echo_mode
&& extraSpace
[0] && (extraSpace
[0] != '@')) {
2169 WCMD_output_asis(extraSpace
);
2170 WCMD_output_asis(newline
);
2175 /* Dump out the parsed output */
2176 WCMD_DumpCommands(*output
);
2181 /***************************************************************************
2182 * WCMD_process_commands
2184 * Process all the commands read in so far
2186 CMD_LIST
*WCMD_process_commands(CMD_LIST
*thisCmd
, BOOL oneBracket
,
2187 const WCHAR
*var
, const WCHAR
*val
) {
2191 if (thisCmd
&& oneBracket
) bdepth
= thisCmd
->bracketDepth
;
2193 /* Loop through the commands, processing them one by one */
2196 CMD_LIST
*origCmd
= thisCmd
;
2198 /* If processing one bracket only, and we find the end bracket
2199 entry (or less), return */
2200 if (oneBracket
&& !thisCmd
->command
&&
2201 bdepth
<= thisCmd
->bracketDepth
) {
2202 WINE_TRACE("Finished bracket @ %p, next command is %p\n",
2203 thisCmd
, thisCmd
->nextcommand
);
2204 return thisCmd
->nextcommand
;
2207 /* Ignore the NULL entries a ')' inserts (Only 'if' cares
2208 about them and it will be handled in there)
2209 Also, skip over any batch labels (eg. :fred) */
2210 if (thisCmd
->command
&& thisCmd
->command
[0] != ':') {
2211 WINE_TRACE("Executing command: '%s'\n", wine_dbgstr_w(thisCmd
->command
));
2212 WCMD_execute (thisCmd
->command
, thisCmd
->redirects
, var
, val
, &thisCmd
);
2215 /* Step on unless the command itself already stepped on */
2216 if (thisCmd
== origCmd
) thisCmd
= thisCmd
->nextcommand
;
2221 /***************************************************************************
2222 * WCMD_free_commands
2224 * Frees the storage held for a parsed command line
2225 * - This is not done in the process_commands, as eventually the current
2226 * pointer will be modified within the commands, and hence a single free
2227 * routine is simpler
2229 void WCMD_free_commands(CMD_LIST
*cmds
) {
2231 /* Loop through the commands, freeing them one by one */
2233 CMD_LIST
*thisCmd
= cmds
;
2234 cmds
= cmds
->nextcommand
;
2235 HeapFree(GetProcessHeap(), 0, thisCmd
->command
);
2236 HeapFree(GetProcessHeap(), 0, thisCmd
->redirects
);
2237 HeapFree(GetProcessHeap(), 0, thisCmd
);
2242 /*****************************************************************************
2243 * Main entry point. This is a console application so we have a main() not a
2247 int wmain (int argc
, WCHAR
*argvW
[])
2255 static const WCHAR promptW
[] = {'P','R','O','M','P','T','\0'};
2256 static const WCHAR defaultpromptW
[] = {'$','P','$','G','\0'};
2257 CMD_LIST
*toExecute
= NULL
; /* Commands left to be executed */
2261 /* Pre initialize some messages */
2262 strcpyW(anykey
, WCMD_LoadMessage(WCMD_ANYKEY
));
2263 cmd
= WCMD_format_string(WCMD_LoadMessage(WCMD_VERSION
), PACKAGE_VERSION
);
2264 strcpyW(version_string
, cmd
);
2269 opt_c
= opt_k
= opt_q
= opt_s
= FALSE
;
2273 WINE_TRACE("Command line parm: '%s'\n", wine_dbgstr_w(*argvW
));
2274 if ((*argvW
)[0]!='/' || (*argvW
)[1]=='\0') {
2281 if (tolowerW(c
)=='c') {
2283 } else if (tolowerW(c
)=='q') {
2285 } else if (tolowerW(c
)=='k') {
2287 } else if (tolowerW(c
)=='s') {
2289 } else if (tolowerW(c
)=='a') {
2290 unicodeOutput
= FALSE
;
2291 } else if (tolowerW(c
)=='u') {
2292 unicodeOutput
= TRUE
;
2293 } else if (tolowerW(c
)=='t' && (*argvW
)[2]==':') {
2294 opt_t
=strtoulW(&(*argvW
)[3], NULL
, 16);
2295 } else if (tolowerW(c
)=='x' || tolowerW(c
)=='y') {
2296 /* Ignored for compatibility with Windows */
2299 if ((*argvW
)[2]==0) {
2303 else /* handle `cmd /cnotepad.exe` and `cmd /x/c ...` */
2308 if (opt_c
|| opt_k
) /* break out of parsing immediately after c or k */
2313 static const WCHAR eoff
[] = {'O','F','F','\0'};
2317 if (opt_c
|| opt_k
) {
2323 /* opt_s left unflagged if the command starts with and contains exactly
2324 * one quoted string (exactly two quote characters). The quoted string
2325 * must be an executable name that has whitespace and must not have the
2326 * following characters: &<>()@^| */
2328 /* Build the command to execute */
2332 for (arg
= argvW
; argsLeft
>0; arg
++,argsLeft
--)
2334 int has_space
,bcount
;
2340 if( !*a
) has_space
=1;
2345 if (*a
==' ' || *a
=='\t') {
2347 } else if (*a
=='"') {
2348 /* doubling of '\' preceding a '"',
2349 * plus escaping of said '"'
2358 len
+=(a
-*arg
) + 1; /* for the separating space */
2361 len
+=2; /* for the quotes */
2369 /* check argvW[0] for a space and invalid characters */
2374 if (*p
=='&' || *p
=='<' || *p
=='>' || *p
=='(' || *p
==')'
2375 || *p
=='@' || *p
=='^' || *p
=='|') {
2385 cmd
= HeapAlloc(GetProcessHeap(), 0, len
* sizeof(WCHAR
));
2391 for (arg
= argvW
; argsLeft
>0; arg
++,argsLeft
--)
2393 int has_space
,has_quote
;
2396 /* Check for quotes and spaces in this argument */
2397 has_space
=has_quote
=0;
2399 if( !*a
) has_space
=1;
2401 if (*a
==' ' || *a
=='\t') {
2405 } else if (*a
=='"') {
2413 /* Now transfer it to the command line */
2430 /* Double all the '\\' preceding this '"', plus one */
2431 for (i
=0;i
<=bcount
;i
++)
2450 p
--; /* remove last space */
2453 WINE_TRACE("/c command line: '%s'\n", wine_dbgstr_w(cmd
));
2455 /* strip first and last quote characters if opt_s; check for invalid
2456 * executable is done later */
2457 if (opt_s
&& *cmd
=='\"')
2458 WCMD_strip_quotes(cmd
);
2462 /* If we do a "cmd /c command", we don't want to allocate a new
2463 * console since the command returns immediately. Rather, we use
2464 * the currently allocated input and output handles. This allows
2465 * us to pipe to and read from the command interpreter.
2468 /* Parse the command string, without reading any more input */
2469 WCMD_ReadAndParseLine(cmd
, &toExecute
, INVALID_HANDLE_VALUE
);
2470 WCMD_process_commands(toExecute
, FALSE
, NULL
, NULL
);
2471 WCMD_free_commands(toExecute
);
2474 HeapFree(GetProcessHeap(), 0, cmd
);
2478 SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE
), ENABLE_LINE_INPUT
|
2479 ENABLE_ECHO_INPUT
| ENABLE_PROCESSED_INPUT
);
2480 SetConsoleTitleW(WCMD_LoadMessage(WCMD_CONSTITLE
));
2482 /* Note: cmd.exe /c dir does not get a new color, /k dir does */
2484 if (!(((opt_t
& 0xF0) >> 4) == (opt_t
& 0x0F))) {
2485 defaultColor
= opt_t
& 0xFF;
2490 /* Check HKCU\Software\Microsoft\Command Processor
2491 Then HKLM\Software\Microsoft\Command Processor
2492 for defaultcolour value
2493 Note Can be supplied as DWORD or REG_SZ
2494 Note2 When supplied as REG_SZ it's in decimal!!! */
2497 DWORD value
=0, size
=4;
2498 static const WCHAR regKeyW
[] = {'S','o','f','t','w','a','r','e','\\',
2499 'M','i','c','r','o','s','o','f','t','\\',
2500 'C','o','m','m','a','n','d',' ','P','r','o','c','e','s','s','o','r','\0'};
2501 static const WCHAR dfltColorW
[] = {'D','e','f','a','u','l','t','C','o','l','o','r','\0'};
2503 if (RegOpenKeyExW(HKEY_CURRENT_USER
, regKeyW
,
2504 0, KEY_READ
, &key
) == ERROR_SUCCESS
) {
2507 /* See if DWORD or REG_SZ */
2508 if (RegQueryValueExW(key
, dfltColorW
, NULL
, &type
,
2509 NULL
, NULL
) == ERROR_SUCCESS
) {
2510 if (type
== REG_DWORD
) {
2511 size
= sizeof(DWORD
);
2512 RegQueryValueExW(key
, dfltColorW
, NULL
, NULL
,
2513 (LPBYTE
)&value
, &size
);
2514 } else if (type
== REG_SZ
) {
2515 size
= sizeof(strvalue
)/sizeof(WCHAR
);
2516 RegQueryValueExW(key
, dfltColorW
, NULL
, NULL
,
2517 (LPBYTE
)strvalue
, &size
);
2518 value
= strtoulW(strvalue
, NULL
, 10);
2524 if (value
== 0 && RegOpenKeyExW(HKEY_LOCAL_MACHINE
, regKeyW
,
2525 0, KEY_READ
, &key
) == ERROR_SUCCESS
) {
2528 /* See if DWORD or REG_SZ */
2529 if (RegQueryValueExW(key
, dfltColorW
, NULL
, &type
,
2530 NULL
, NULL
) == ERROR_SUCCESS
) {
2531 if (type
== REG_DWORD
) {
2532 size
= sizeof(DWORD
);
2533 RegQueryValueExW(key
, dfltColorW
, NULL
, NULL
,
2534 (LPBYTE
)&value
, &size
);
2535 } else if (type
== REG_SZ
) {
2536 size
= sizeof(strvalue
)/sizeof(WCHAR
);
2537 RegQueryValueExW(key
, dfltColorW
, NULL
, NULL
,
2538 (LPBYTE
)strvalue
, &size
);
2539 value
= strtoulW(strvalue
, NULL
, 10);
2545 /* If one found, set the screen to that colour */
2546 if (!(((value
& 0xF0) >> 4) == (value
& 0x0F))) {
2547 defaultColor
= value
& 0xFF;
2554 /* Save cwd into appropriate env var */
2555 GetCurrentDirectoryW(1024, string
);
2556 if (IsCharAlphaW(string
[0]) && string
[1] == ':') {
2557 static const WCHAR fmt
[] = {'=','%','c',':','\0'};
2558 wsprintfW(envvar
, fmt
, string
[0]);
2559 SetEnvironmentVariableW(envvar
, string
);
2560 WINE_TRACE("Set %s to %s\n", wine_dbgstr_w(envvar
), wine_dbgstr_w(string
));
2564 /* Parse the command string, without reading any more input */
2565 WCMD_ReadAndParseLine(cmd
, &toExecute
, INVALID_HANDLE_VALUE
);
2566 WCMD_process_commands(toExecute
, FALSE
, NULL
, NULL
);
2567 WCMD_free_commands(toExecute
);
2569 HeapFree(GetProcessHeap(), 0, cmd
);
2573 * Loop forever getting commands and executing them.
2576 SetEnvironmentVariableW(promptW
, defaultpromptW
);
2580 /* Read until EOF (which for std input is never, but if redirect
2581 in place, may occur */
2582 if (echo_mode
) WCMD_show_prompt();
2583 if (!WCMD_ReadAndParseLine(NULL
, &toExecute
, GetStdHandle(STD_INPUT_HANDLE
)))
2585 WCMD_process_commands(toExecute
, FALSE
, NULL
, NULL
);
2586 WCMD_free_commands(toExecute
);