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 const WCHAR inbuilt
[][10] = {
35 {'C','A','L','L','\0'},
37 {'C','H','D','I','R','\0'},
39 {'C','O','P','Y','\0'},
40 {'C','T','T','Y','\0'},
41 {'D','A','T','E','\0'},
44 {'E','C','H','O','\0'},
45 {'E','R','A','S','E','\0'},
47 {'G','O','T','O','\0'},
48 {'H','E','L','P','\0'},
50 {'L','A','B','E','L','\0'},
52 {'M','K','D','I','R','\0'},
53 {'M','O','V','E','\0'},
54 {'P','A','T','H','\0'},
55 {'P','A','U','S','E','\0'},
56 {'P','R','O','M','P','T','\0'},
59 {'R','E','N','A','M','E','\0'},
61 {'R','M','D','I','R','\0'},
63 {'S','H','I','F','T','\0'},
64 {'T','I','M','E','\0'},
65 {'T','I','T','L','E','\0'},
66 {'T','Y','P','E','\0'},
67 {'V','E','R','I','F','Y','\0'},
70 {'E','N','D','L','O','C','A','L','\0'},
71 {'S','E','T','L','O','C','A','L','\0'},
72 {'P','U','S','H','D','\0'},
73 {'P','O','P','D','\0'},
74 {'A','S','S','O','C','\0'},
75 {'C','O','L','O','R','\0'},
76 {'F','T','Y','P','E','\0'},
77 {'M','O','R','E','\0'},
78 {'C','H','O','I','C','E','\0'},
79 {'E','X','I','T','\0'}
82 const WCHAR externals
[NUM_EXTERNALS
][10] = {
83 {'A','T','T','R','I','B','\0'},
84 {'X','C','O','P','Y','\0'}
90 BOOL echo_mode
= TRUE
;
91 static int opt_c
, opt_k
, opt_s
;
92 const WCHAR newline
[] = {'\r','\n','\0'};
93 static const WCHAR equalsW
[] = {'=','\0'};
94 static const WCHAR closeBW
[] = {')','\0'};
96 WCHAR version_string
[100];
97 WCHAR quals
[MAX_PATH
], param1
[MAXSTRING
], param2
[MAXSTRING
];
98 BATCH_CONTEXT
*context
= NULL
;
99 extern struct env_stack
*pushd_directories
;
100 static const WCHAR
*pagedMessage
= NULL
;
101 static char *output_bufA
= NULL
;
102 #define MAX_WRITECONSOLE_SIZE 65535
103 static BOOL unicodePipes
= FALSE
;
106 * Returns a buffer for reading from/writing to file
109 static char *get_file_buffer(void)
112 output_bufA
= HeapAlloc(GetProcessHeap(), 0, MAX_WRITECONSOLE_SIZE
);
114 WINE_FIXME("Out of memory - could not allocate ansi 64K buffer\n");
119 /*******************************************************************
120 * WCMD_output_asis_len - send output to current standard output
122 * Output a formatted unicode string. Ideally this will go to the console
123 * and hence required WriteConsoleW to output it, however if file i/o is
124 * redirected, it needs to be WriteFile'd using OEM (not ANSI) format
126 static void WCMD_output_asis_len(const WCHAR
*message
, int len
, HANDLE device
) {
131 /* If nothing to write, return (MORE does this sometimes) */
134 /* Try to write as unicode assuming it is to a console */
135 res
= WriteConsoleW(device
, message
, len
, &nOut
, NULL
);
137 /* If writing to console fails, assume its file
138 i/o so convert to OEM codepage and output */
140 BOOL usedDefaultChar
= FALSE
;
141 DWORD convertedChars
;
146 if (!(buffer
= get_file_buffer()))
149 /* Convert to OEM, then output */
150 convertedChars
= WideCharToMultiByte(GetConsoleOutputCP(), 0, message
,
151 len
, buffer
, MAX_WRITECONSOLE_SIZE
,
152 "?", &usedDefaultChar
);
153 WriteFile(device
, buffer
, convertedChars
,
156 WriteFile(device
, message
, len
*sizeof(WCHAR
),
163 /*******************************************************************
164 * WCMD_output - send output to current standard output device.
168 void WCMD_output (const WCHAR
*format
, ...) {
175 ret
= vsnprintfW(string
, sizeof(string
)/sizeof(WCHAR
), format
, ap
);
176 if( ret
>= (sizeof(string
)/sizeof(WCHAR
))) {
177 WINE_ERR("Output truncated\n" );
178 ret
= (sizeof(string
)/sizeof(WCHAR
)) - 1;
182 WCMD_output_asis_len(string
, ret
, GetStdHandle(STD_OUTPUT_HANDLE
));
185 /*******************************************************************
186 * WCMD_output_stderr - send output to current standard error device.
190 void WCMD_output_stderr (const WCHAR
*format
, ...) {
197 ret
= vsnprintfW(string
, sizeof(string
)/sizeof(WCHAR
), format
, ap
);
198 if( ret
>= (sizeof(string
)/sizeof(WCHAR
))) {
199 WINE_ERR("Output truncated\n" );
200 ret
= (sizeof(string
)/sizeof(WCHAR
)) - 1;
204 WCMD_output_asis_len(string
, ret
, GetStdHandle(STD_ERROR_HANDLE
));
207 static int line_count
;
208 static int max_height
;
209 static int max_width
;
210 static BOOL paged_mode
;
213 void WCMD_enter_paged_mode(const WCHAR
*msg
)
215 CONSOLE_SCREEN_BUFFER_INFO consoleInfo
;
217 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE
), &consoleInfo
)) {
218 max_height
= consoleInfo
.dwSize
.Y
;
219 max_width
= consoleInfo
.dwSize
.X
;
227 pagedMessage
= (msg
==NULL
)? anykey
: msg
;
230 void WCMD_leave_paged_mode(void)
236 /***************************************************************************
239 * Read characters in from a console/file, returning result in Unicode
240 * with signature identical to ReadFile
242 BOOL
WCMD_ReadFile(const HANDLE hIn
, WCHAR
*intoBuf
, const DWORD maxChars
,
243 LPDWORD charsRead
, const LPOVERLAPPED unused
) {
247 /* Try to read from console as Unicode */
248 res
= ReadConsoleW(hIn
, intoBuf
, maxChars
, charsRead
, NULL
);
250 /* If reading from console has failed we assume its file
251 i/o so read in and convert from OEM codepage */
257 if (!(buffer
= get_file_buffer()))
260 /* Read from file (assume OEM codepage) */
261 res
= ReadFile(hIn
, buffer
, maxChars
, &numRead
, unused
);
263 /* Convert from OEM */
264 *charsRead
= MultiByteToWideChar(GetConsoleCP(), 0, buffer
, numRead
,
271 /*******************************************************************
272 * WCMD_output_asis_handle
274 * Send output to specified handle without formatting e.g. when message contains '%'
276 static void WCMD_output_asis_handle (DWORD std_handle
, const WCHAR
*message
) {
280 HANDLE handle
= GetStdHandle(std_handle
);
285 while (*ptr
&& *ptr
!='\n' && (numChars
< max_width
)) {
289 if (*ptr
== '\n') ptr
++;
290 WCMD_output_asis_len(message
, (ptr
) ? ptr
- message
: strlenW(message
), handle
);
293 if (++line_count
>= max_height
- 1) {
295 WCMD_output_asis_len(pagedMessage
, strlenW(pagedMessage
), handle
);
296 WCMD_ReadFile (GetStdHandle(STD_INPUT_HANDLE
), string
,
297 sizeof(string
)/sizeof(WCHAR
), &count
, NULL
);
300 } while (((message
= ptr
) != NULL
) && (*ptr
));
302 WCMD_output_asis_len(message
, lstrlenW(message
), handle
);
306 /*******************************************************************
309 * Send output to current standard output device, without formatting
310 * e.g. when message contains '%'
312 void WCMD_output_asis (const WCHAR
*message
) {
313 WCMD_output_asis_handle(STD_OUTPUT_HANDLE
, message
);
316 /*******************************************************************
317 * WCMD_output_asis_stderr
319 * Send output to current standard error device, without formatting
320 * e.g. when message contains '%'
322 void WCMD_output_asis_stderr (const WCHAR
*message
) {
323 WCMD_output_asis_handle(STD_ERROR_HANDLE
, message
);
326 /****************************************************************************
329 * Print the message for GetLastError
332 void WCMD_print_error (void) {
337 error_code
= GetLastError ();
338 status
= FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
,
339 NULL
, error_code
, 0, (LPWSTR
) &lpMsgBuf
, 0, NULL
);
341 WINE_FIXME ("Cannot display message for error %d, status %d\n",
342 error_code
, GetLastError());
346 WCMD_output_asis_len(lpMsgBuf
, lstrlenW(lpMsgBuf
),
347 GetStdHandle(STD_ERROR_HANDLE
));
348 LocalFree (lpMsgBuf
);
349 WCMD_output_asis_len (newline
, lstrlenW(newline
),
350 GetStdHandle(STD_ERROR_HANDLE
));
354 /******************************************************************************
357 * Display the prompt on STDout
361 static void WCMD_show_prompt (void) {
364 WCHAR out_string
[MAX_PATH
], curdir
[MAX_PATH
], prompt_string
[MAX_PATH
];
367 static const WCHAR envPrompt
[] = {'P','R','O','M','P','T','\0'};
369 len
= GetEnvironmentVariableW(envPrompt
, prompt_string
,
370 sizeof(prompt_string
)/sizeof(WCHAR
));
371 if ((len
== 0) || (len
>= (sizeof(prompt_string
)/sizeof(WCHAR
)))) {
372 static const WCHAR dfltPrompt
[] = {'$','P','$','G','\0'};
373 strcpyW (prompt_string
, dfltPrompt
);
387 switch (toupper(*p
)) {
401 GetDateFormatW(LOCALE_USER_DEFAULT
, DATE_SHORTDATE
, NULL
, NULL
, q
, MAX_PATH
);
420 status
= GetCurrentDirectoryW(sizeof(curdir
)/sizeof(WCHAR
), curdir
);
426 status
= GetCurrentDirectoryW(sizeof(curdir
)/sizeof(WCHAR
), curdir
);
439 GetTimeFormatW(LOCALE_USER_DEFAULT
, 0, NULL
, NULL
, q
, MAX_PATH
);
443 strcatW (q
, version_string
);
450 if (pushd_directories
) {
451 memset(q
, '+', pushd_directories
->u
.stackdepth
);
452 q
= q
+ pushd_directories
->u
.stackdepth
;
460 WCMD_output_asis (out_string
);
464 /*************************************************************************
466 * A wide version of strdup as its missing from unicode.h
468 WCHAR
*WCMD_strdupW(const WCHAR
*input
) {
469 int len
=strlenW(input
)+1;
470 WCHAR
*result
= HeapAlloc(GetProcessHeap(), 0, len
* sizeof(WCHAR
));
471 memcpy(result
, input
, len
* sizeof(WCHAR
));
475 /*************************************************************************
477 * Replaces a portion of a Unicode string with the specified string.
478 * It's up to the caller to ensure there is enough space in the
479 * destination buffer.
481 void WCMD_strsubstW(WCHAR
*start
, const WCHAR
*next
, const WCHAR
*insert
, int len
) {
484 len
=insert
? lstrlenW(insert
) : 0;
485 if (start
+len
!= next
)
486 memmove(start
+len
, next
, (strlenW(next
) + 1) * sizeof(*next
));
488 memcpy(start
, insert
, len
* sizeof(*insert
));
491 /***************************************************************************
492 * WCMD_skip_leading_spaces
494 * Return a pointer to the first non-whitespace character of string.
495 * Does not modify the input string.
497 WCHAR
*WCMD_skip_leading_spaces (WCHAR
*string
) {
502 while (*ptr
== ' ' || *ptr
== '\t') ptr
++;
506 /***************************************************************************
507 * WCMD_keyword_ws_found
509 * Checks if the string located at ptr matches a keyword (of length len)
510 * followed by a whitespace character (space or tab)
512 BOOL
WCMD_keyword_ws_found(const WCHAR
*keyword
, int len
, const WCHAR
*ptr
) {
513 return (CompareStringW(LOCALE_USER_DEFAULT
, NORM_IGNORECASE
| SORT_STRINGSORT
,
514 ptr
, len
, keyword
, len
) == CSTR_EQUAL
)
515 && ((*(ptr
+ len
) == ' ') || (*(ptr
+ len
) == '\t'));
518 /*************************************************************************
519 * WCMD_opt_s_strip_quotes
521 * Remove first and last quote WCHARacters, preserving all other text
523 void WCMD_opt_s_strip_quotes(WCHAR
*cmd
) {
524 WCHAR
*src
= cmd
+ 1, *dest
= cmd
, *lastq
= NULL
;
525 while((*dest
=*src
) != '\0') {
532 while ((*dest
++=*lastq
++) != 0)
538 /*************************************************************************
539 * WCMD_is_magic_envvar
540 * Return TRUE if s is '%'magicvar'%'
541 * and is not masked by a real environment variable.
544 static inline BOOL
WCMD_is_magic_envvar(const WCHAR
*s
, const WCHAR
*magicvar
)
549 return FALSE
; /* Didn't begin with % */
551 if (len
< 2 || s
[len
-1] != '%')
552 return FALSE
; /* Didn't end with another % */
554 if (CompareStringW(LOCALE_USER_DEFAULT
,
555 NORM_IGNORECASE
| SORT_STRINGSORT
,
556 s
+1, len
-2, magicvar
, -1) != CSTR_EQUAL
) {
557 /* Name doesn't match. */
561 if (GetEnvironmentVariableW(magicvar
, NULL
, 0) > 0) {
562 /* Masked by real environment variable. */
569 /*************************************************************************
572 * Expands environment variables, allowing for WCHARacter substitution
574 static WCHAR
*WCMD_expand_envvar(WCHAR
*start
,
575 const WCHAR
*forVar
, const WCHAR
*forVal
) {
576 WCHAR
*endOfVar
= NULL
, *s
;
577 WCHAR
*colonpos
= NULL
;
578 WCHAR thisVar
[MAXSTRING
];
579 WCHAR thisVarContents
[MAXSTRING
];
580 WCHAR savedchar
= 0x00;
583 static const WCHAR ErrorLvl
[] = {'E','R','R','O','R','L','E','V','E','L','\0'};
584 static const WCHAR Date
[] = {'D','A','T','E','\0'};
585 static const WCHAR Time
[] = {'T','I','M','E','\0'};
586 static const WCHAR Cd
[] = {'C','D','\0'};
587 static const WCHAR Random
[] = {'R','A','N','D','O','M','\0'};
588 static const WCHAR Delims
[] = {'%',' ',':','\0'};
590 WINE_TRACE("Expanding: %s (%s,%s)\n", wine_dbgstr_w(start
),
591 wine_dbgstr_w(forVal
), wine_dbgstr_w(forVar
));
593 /* Find the end of the environment variable, and extract name */
594 endOfVar
= strpbrkW(start
+1, Delims
);
596 if (endOfVar
== NULL
|| *endOfVar
==' ') {
598 /* In batch program, missing terminator for % and no following
599 ':' just removes the '%' */
601 WCMD_strsubstW(start
, start
+ 1, NULL
, 0);
605 /* In command processing, just ignore it - allows command line
606 syntax like: for %i in (a.a) do echo %i */
611 /* If ':' found, process remaining up until '%' (or stop at ':' if
613 if (*endOfVar
==':') {
614 WCHAR
*endOfVar2
= strchrW(endOfVar
+1, '%');
615 if (endOfVar2
!= NULL
) endOfVar
= endOfVar2
;
618 memcpy(thisVar
, start
, ((endOfVar
- start
) + 1) * sizeof(WCHAR
));
619 thisVar
[(endOfVar
- start
)+1] = 0x00;
620 colonpos
= strchrW(thisVar
+1, ':');
622 /* If there's complex substitution, just need %var% for now
623 to get the expanded data to play with */
626 savedchar
= *(colonpos
+1);
627 *(colonpos
+1) = 0x00;
630 WINE_TRACE("Retrieving contents of %s\n", wine_dbgstr_w(thisVar
));
632 /* Expand to contents, if unchanged, return */
633 /* Handle DATE, TIME, ERRORLEVEL and CD replacements allowing */
634 /* override if existing env var called that name */
635 if (WCMD_is_magic_envvar(thisVar
, ErrorLvl
)) {
636 static const WCHAR fmt
[] = {'%','d','\0'};
637 wsprintfW(thisVarContents
, fmt
, errorlevel
);
638 len
= strlenW(thisVarContents
);
639 } else if (WCMD_is_magic_envvar(thisVar
, Date
)) {
640 GetDateFormatW(LOCALE_USER_DEFAULT
, DATE_SHORTDATE
, NULL
,
641 NULL
, thisVarContents
, MAXSTRING
);
642 len
= strlenW(thisVarContents
);
643 } else if (WCMD_is_magic_envvar(thisVar
, Time
)) {
644 GetTimeFormatW(LOCALE_USER_DEFAULT
, TIME_NOSECONDS
, NULL
,
645 NULL
, thisVarContents
, MAXSTRING
);
646 len
= strlenW(thisVarContents
);
647 } else if (WCMD_is_magic_envvar(thisVar
, Cd
)) {
648 GetCurrentDirectoryW(MAXSTRING
, thisVarContents
);
649 len
= strlenW(thisVarContents
);
650 } else if (WCMD_is_magic_envvar(thisVar
, Random
)) {
651 static const WCHAR fmt
[] = {'%','d','\0'};
652 wsprintfW(thisVarContents
, fmt
, rand() % 32768);
653 len
= strlenW(thisVarContents
);
655 /* Look for a matching 'for' variable */
657 (CompareStringW(LOCALE_USER_DEFAULT
,
660 (colonpos
- thisVar
) - 1,
661 forVar
, -1) == CSTR_EQUAL
)) {
662 strcpyW(thisVarContents
, forVal
);
663 len
= strlenW(thisVarContents
);
667 len
= ExpandEnvironmentStringsW(thisVar
, thisVarContents
,
668 sizeof(thisVarContents
)/sizeof(WCHAR
));
674 /* In a batch program, unknown env vars are replaced with nothing,
675 note syntax %garbage:1,3% results in anything after the ':'
677 From the command line, you just get back what you entered */
678 if (lstrcmpiW(thisVar
, thisVarContents
) == 0) {
680 /* Restore the complex part after the compare */
683 *(colonpos
+1) = savedchar
;
686 /* Command line - just ignore this */
687 if (context
== NULL
) return endOfVar
+1;
690 /* Batch - replace unknown env var with nothing */
691 if (colonpos
== NULL
) {
692 WCMD_strsubstW(start
, endOfVar
+ 1, NULL
, 0);
694 len
= strlenW(thisVar
);
695 thisVar
[len
-1] = 0x00;
696 /* If %:...% supplied, : is retained */
697 if (colonpos
== thisVar
+1) {
698 WCMD_strsubstW(start
, endOfVar
+ 1, colonpos
, -1);
700 WCMD_strsubstW(start
, endOfVar
+ 1, colonpos
+ 1, -1);
707 /* See if we need to do complex substitution (any ':'s), if not
708 then our work here is done */
709 if (colonpos
== NULL
) {
710 WCMD_strsubstW(start
, endOfVar
+ 1, thisVarContents
, -1);
714 /* Restore complex bit */
716 *(colonpos
+1) = savedchar
;
719 Handle complex substitutions:
720 xxx=yyy (replace xxx with yyy)
721 *xxx=yyy (replace up to and including xxx with yyy)
722 ~x (from x WCHARs in)
723 ~-x (from x WCHARs from the end)
724 ~x,y (from x WCHARs in for y WCHARacters)
725 ~x,-y (from x WCHARs in until y WCHARacters from the end)
728 /* ~ is substring manipulation */
729 if (savedchar
== '~') {
731 int substrposition
, substrlength
= 0;
732 WCHAR
*commapos
= strchrW(colonpos
+2, ',');
735 substrposition
= atolW(colonpos
+2);
736 if (commapos
) substrlength
= atolW(commapos
+1);
739 if (substrposition
>= 0) {
740 startCopy
= &thisVarContents
[min(substrposition
, len
)];
742 startCopy
= &thisVarContents
[max(0, len
+substrposition
-1)];
745 if (commapos
== NULL
) {
747 WCMD_strsubstW(start
, endOfVar
+ 1, startCopy
, -1);
748 } else if (substrlength
< 0) {
750 int copybytes
= (len
+substrlength
-1)-(startCopy
-thisVarContents
);
751 if (copybytes
> len
) copybytes
= len
;
752 else if (copybytes
< 0) copybytes
= 0;
753 WCMD_strsubstW(start
, endOfVar
+ 1, startCopy
, copybytes
);
755 WCMD_strsubstW(start
, endOfVar
+ 1, startCopy
, substrlength
);
760 /* search and replace manipulation */
762 WCHAR
*equalspos
= strstrW(colonpos
, equalsW
);
763 WCHAR
*replacewith
= equalspos
+1;
768 if (equalspos
== NULL
) return start
+1;
769 s
= WCMD_strdupW(endOfVar
+ 1);
771 /* Null terminate both strings */
772 thisVar
[strlenW(thisVar
)-1] = 0x00;
775 /* Since we need to be case insensitive, copy the 2 buffers */
776 searchIn
= WCMD_strdupW(thisVarContents
);
777 CharUpperBuffW(searchIn
, strlenW(thisVarContents
));
778 searchFor
= WCMD_strdupW(colonpos
+1);
779 CharUpperBuffW(searchFor
, strlenW(colonpos
+1));
781 /* Handle wildcard case */
782 if (*(colonpos
+1) == '*') {
783 /* Search for string to replace */
784 found
= strstrW(searchIn
, searchFor
+1);
788 strcpyW(start
, replacewith
);
789 strcatW(start
, thisVarContents
+ (found
-searchIn
) + strlenW(searchFor
+1));
793 strcpyW(start
, thisVarContents
);
798 /* Loop replacing all instances */
799 WCHAR
*lastFound
= searchIn
;
800 WCHAR
*outputposn
= start
;
803 while ((found
= strstrW(lastFound
, searchFor
))) {
804 lstrcpynW(outputposn
,
805 thisVarContents
+ (lastFound
-searchIn
),
806 (found
- lastFound
)+1);
807 outputposn
= outputposn
+ (found
- lastFound
);
808 strcatW(outputposn
, replacewith
);
809 outputposn
= outputposn
+ strlenW(replacewith
);
810 lastFound
= found
+ strlenW(searchFor
);
813 thisVarContents
+ (lastFound
-searchIn
));
814 strcatW(outputposn
, s
);
816 HeapFree(GetProcessHeap(), 0, s
);
817 HeapFree(GetProcessHeap(), 0, searchIn
);
818 HeapFree(GetProcessHeap(), 0, searchFor
);
824 /*****************************************************************************
825 * Expand the command. Native expands lines from batch programs as they are
826 * read in and not again, except for 'for' variable substitution.
827 * eg. As evidence, "echo %1 && shift && echo %1" or "echo %%path%%"
829 static void handleExpansion(WCHAR
*cmd
, BOOL justFors
,
830 const WCHAR
*forVariable
, const WCHAR
*forValue
) {
832 /* For commands in a context (batch program): */
833 /* Expand environment variables in a batch file %{0-9} first */
834 /* including support for any ~ modifiers */
836 /* Expand the DATE, TIME, CD, RANDOM and ERRORLEVEL special */
837 /* names allowing environment variable overrides */
838 /* NOTE: To support the %PATH:xxx% syntax, also perform */
839 /* manual expansion of environment variables here */
845 while ((p
= strchrW(p
, '%'))) {
847 WINE_TRACE("Translate command:%s %d (at: %s)\n",
848 wine_dbgstr_w(cmd
), justFors
, wine_dbgstr_w(p
));
851 /* Don't touch %% unless its in Batch */
852 if (!justFors
&& *(p
+1) == '%') {
854 WCMD_strsubstW(p
, p
+1, NULL
, 0);
858 /* Replace %~ modifications if in batch program */
859 } else if (*(p
+1) == '~') {
860 WCMD_HandleTildaModifiers(&p
, forVariable
, forValue
, justFors
);
863 /* Replace use of %0...%9 if in batch program*/
864 } else if (!justFors
&& context
&& (i
>= 0) && (i
<= 9)) {
865 t
= WCMD_parameter(context
-> command
, i
+ context
-> shift_count
[i
], NULL
, NULL
);
866 WCMD_strsubstW(p
, p
+2, t
, -1);
868 /* Replace use of %* if in batch program*/
869 } else if (!justFors
&& context
&& *(p
+1)=='*') {
870 WCHAR
*startOfParms
= NULL
;
871 t
= WCMD_parameter(context
-> command
, 1, &startOfParms
, NULL
);
872 if (startOfParms
!= NULL
)
873 WCMD_strsubstW(p
, p
+2, startOfParms
, -1);
875 WCMD_strsubstW(p
, p
+2, NULL
, 0);
877 } else if (forVariable
&&
878 (CompareStringW(LOCALE_USER_DEFAULT
,
881 strlenW(forVariable
),
882 forVariable
, -1) == CSTR_EQUAL
)) {
883 WCMD_strsubstW(p
, p
+ strlenW(forVariable
), forValue
, -1);
885 } else if (!justFors
) {
886 p
= WCMD_expand_envvar(p
, forVariable
, forValue
);
888 /* In a FOR loop, see if this is the variable to replace */
889 } else { /* Ignore %'s on second pass of batch program */
898 /*******************************************************************
899 * WCMD_parse - parse a command into parameters and qualifiers.
901 * On exit, all qualifiers are concatenated into q, the first string
902 * not beginning with "/" is in p1 and the
903 * second in p2. Any subsequent non-qualifier strings are lost.
904 * Parameters in quotes are handled.
906 static void WCMD_parse (const WCHAR
*s
, WCHAR
*q
, WCHAR
*p1
, WCHAR
*p2
)
910 *q
= *p1
= *p2
= '\0';
915 while ((*s
!= '\0') && (*s
!= ' ') && *s
!= '/') {
916 *q
++ = toupperW (*s
++);
926 while ((*s
!= '\0') && (*s
!= '"')) {
927 if (p
== 0) *p1
++ = *s
++;
928 else if (p
== 1) *p2
++ = *s
++;
931 if (p
== 0) *p1
= '\0';
932 if (p
== 1) *p2
= '\0';
939 while ((*s
!= '\0') && (*s
!= ' ') && (*s
!= '\t')
940 && (*s
!= '=') && (*s
!= ',') ) {
941 if (p
== 0) *p1
++ = *s
++;
942 else if (p
== 1) *p2
++ = *s
++;
945 /* Skip concurrent parms */
946 while ((*s
== ' ') || (*s
== '\t') || (*s
== '=') || (*s
== ',') ) s
++;
948 if (p
== 0) *p1
= '\0';
949 if (p
== 1) *p2
= '\0';
955 static void init_msvcrt_io_block(STARTUPINFOW
* st
)
958 /* fetch the parent MSVCRT info block if any, so that the child can use the
959 * same handles as its grand-father
961 st_p
.cb
= sizeof(STARTUPINFOW
);
962 GetStartupInfoW(&st_p
);
963 st
->cbReserved2
= st_p
.cbReserved2
;
964 st
->lpReserved2
= st_p
.lpReserved2
;
965 if (st_p
.cbReserved2
&& st_p
.lpReserved2
)
967 /* Override the entries for fd 0,1,2 if we happened
968 * to change those std handles (this depends on the way cmd sets
969 * its new input & output handles)
971 size_t sz
= max(sizeof(unsigned) + (sizeof(char) + sizeof(HANDLE
)) * 3, st_p
.cbReserved2
);
972 BYTE
* ptr
= HeapAlloc(GetProcessHeap(), 0, sz
);
975 unsigned num
= *(unsigned*)st_p
.lpReserved2
;
976 char* flags
= (char*)(ptr
+ sizeof(unsigned));
977 HANDLE
* handles
= (HANDLE
*)(flags
+ num
* sizeof(char));
979 memcpy(ptr
, st_p
.lpReserved2
, st_p
.cbReserved2
);
980 st
->cbReserved2
= sz
;
981 st
->lpReserved2
= ptr
;
983 #define WX_OPEN 0x01 /* see dlls/msvcrt/file.c */
984 if (num
<= 0 || (flags
[0] & WX_OPEN
))
986 handles
[0] = GetStdHandle(STD_INPUT_HANDLE
);
989 if (num
<= 1 || (flags
[1] & WX_OPEN
))
991 handles
[1] = GetStdHandle(STD_OUTPUT_HANDLE
);
994 if (num
<= 2 || (flags
[2] & WX_OPEN
))
996 handles
[2] = GetStdHandle(STD_ERROR_HANDLE
);
1004 /******************************************************************************
1007 * Execute a command line as an external program. Must allow recursion.
1010 * Manual testing under windows shows PATHEXT plays a key part in this,
1011 * and the search algorithm and precedence appears to be as follows.
1014 * If directory supplied on command, just use that directory
1015 * If extension supplied on command, look for that explicit name first
1016 * Otherwise, search in each directory on the path
1018 * If extension supplied on command, look for that explicit name first
1019 * Then look for supplied name .* (even if extension supplied, so
1020 * 'garbage.exe' will match 'garbage.exe.cmd')
1021 * If any found, cycle through PATHEXT looking for name.exe one by one
1023 * Once a match has been found, it is launched - Code currently uses
1024 * findexecutable to achieve this which is left untouched.
1027 void WCMD_run_program (WCHAR
*command
, int called
) {
1029 WCHAR temp
[MAX_PATH
];
1030 WCHAR pathtosearch
[MAXSTRING
];
1032 WCHAR stemofsearch
[MAX_PATH
]; /* maximum allowed executable name is
1033 MAX_PATH, including null character */
1035 WCHAR pathext
[MAXSTRING
];
1036 BOOL extensionsupplied
= FALSE
;
1037 BOOL launched
= FALSE
;
1039 BOOL assumeInternal
= FALSE
;
1041 static const WCHAR envPath
[] = {'P','A','T','H','\0'};
1042 static const WCHAR envPathExt
[] = {'P','A','T','H','E','X','T','\0'};
1043 static const WCHAR delims
[] = {'/','\\',':','\0'};
1045 WCMD_parse (command
, quals
, param1
, param2
); /* Quick way to get the filename */
1046 if (!(*param1
) && !(*param2
))
1049 /* Calculate the search path and stem to search for */
1050 if (strpbrkW (param1
, delims
) == NULL
) { /* No explicit path given, search path */
1051 static const WCHAR curDir
[] = {'.',';','\0'};
1052 strcpyW(pathtosearch
, curDir
);
1053 len
= GetEnvironmentVariableW(envPath
, &pathtosearch
[2], (sizeof(pathtosearch
)/sizeof(WCHAR
))-2);
1054 if ((len
== 0) || (len
>= (sizeof(pathtosearch
)/sizeof(WCHAR
)) - 2)) {
1055 static const WCHAR curDir
[] = {'.','\0'};
1056 strcpyW (pathtosearch
, curDir
);
1058 if (strchrW(param1
, '.') != NULL
) extensionsupplied
= TRUE
;
1059 if (strlenW(param1
) >= MAX_PATH
)
1061 WCMD_output_asis(WCMD_LoadMessage(WCMD_LINETOOLONG
));
1065 strcpyW(stemofsearch
, param1
);
1069 /* Convert eg. ..\fred to include a directory by removing file part */
1070 GetFullPathNameW(param1
, sizeof(pathtosearch
)/sizeof(WCHAR
), pathtosearch
, NULL
);
1071 lastSlash
= strrchrW(pathtosearch
, '\\');
1072 if (lastSlash
&& strchrW(lastSlash
, '.') != NULL
) extensionsupplied
= TRUE
;
1073 strcpyW(stemofsearch
, lastSlash
+1);
1075 /* Reduce pathtosearch to a path with trailing '\' to support c:\a.bat and
1076 c:\windows\a.bat syntax */
1077 if (lastSlash
) *(lastSlash
+ 1) = 0x00;
1080 /* Now extract PATHEXT */
1081 len
= GetEnvironmentVariableW(envPathExt
, pathext
, sizeof(pathext
)/sizeof(WCHAR
));
1082 if ((len
== 0) || (len
>= (sizeof(pathext
)/sizeof(WCHAR
)))) {
1083 static const WCHAR dfltPathExt
[] = {'.','b','a','t',';',
1084 '.','c','o','m',';',
1085 '.','c','m','d',';',
1086 '.','e','x','e','\0'};
1087 strcpyW (pathext
, dfltPathExt
);
1090 /* Loop through the search path, dir by dir */
1091 pathposn
= pathtosearch
;
1092 WINE_TRACE("Searching in '%s' for '%s'\n", wine_dbgstr_w(pathtosearch
),
1093 wine_dbgstr_w(stemofsearch
));
1094 while (!launched
&& pathposn
) {
1096 WCHAR thisDir
[MAX_PATH
] = {'\0'};
1099 static const WCHAR slashW
[] = {'\\','\0'};
1101 /* Work on the first directory on the search path */
1102 pos
= strchrW(pathposn
, ';');
1104 memcpy(thisDir
, pathposn
, (pos
-pathposn
) * sizeof(WCHAR
));
1105 thisDir
[(pos
-pathposn
)] = 0x00;
1109 strcpyW(thisDir
, pathposn
);
1113 /* Since you can have eg. ..\.. on the path, need to expand
1114 to full information */
1115 strcpyW(temp
, thisDir
);
1116 GetFullPathNameW(temp
, MAX_PATH
, thisDir
, NULL
);
1118 /* 1. If extension supplied, see if that file exists */
1119 strcatW(thisDir
, slashW
);
1120 strcatW(thisDir
, stemofsearch
);
1121 pos
= &thisDir
[strlenW(thisDir
)]; /* Pos = end of name */
1123 /* 1. If extension supplied, see if that file exists */
1124 if (extensionsupplied
) {
1125 if (GetFileAttributesW(thisDir
) != INVALID_FILE_ATTRIBUTES
) {
1130 /* 2. Any .* matches? */
1133 WIN32_FIND_DATAW finddata
;
1134 static const WCHAR allFiles
[] = {'.','*','\0'};
1136 strcatW(thisDir
,allFiles
);
1137 h
= FindFirstFileW(thisDir
, &finddata
);
1139 if (h
!= INVALID_HANDLE_VALUE
) {
1141 WCHAR
*thisExt
= pathext
;
1143 /* 3. Yes - Try each path ext */
1145 WCHAR
*nextExt
= strchrW(thisExt
, ';');
1148 memcpy(pos
, thisExt
, (nextExt
-thisExt
) * sizeof(WCHAR
));
1149 pos
[(nextExt
-thisExt
)] = 0x00;
1150 thisExt
= nextExt
+1;
1152 strcpyW(pos
, thisExt
);
1156 if (GetFileAttributesW(thisDir
) != INVALID_FILE_ATTRIBUTES
) {
1164 /* Internal programs won't be picked up by this search, so even
1165 though not found, try one last createprocess and wait for it
1167 Note: Ideally we could tell between a console app (wait) and a
1168 windows app, but the API's for it fail in this case */
1169 if (!found
&& pathposn
== NULL
) {
1170 WINE_TRACE("ASSUMING INTERNAL\n");
1171 assumeInternal
= TRUE
;
1173 WINE_TRACE("Found as %s\n", wine_dbgstr_w(thisDir
));
1176 /* Once found, launch it */
1177 if (found
|| assumeInternal
) {
1179 PROCESS_INFORMATION pe
;
1183 WCHAR
*ext
= strrchrW( thisDir
, '.' );
1184 static const WCHAR batExt
[] = {'.','b','a','t','\0'};
1185 static const WCHAR cmdExt
[] = {'.','c','m','d','\0'};
1189 /* Special case BAT and CMD */
1190 if (ext
&& !strcmpiW(ext
, batExt
)) {
1191 WCMD_batch (thisDir
, command
, called
, NULL
, INVALID_HANDLE_VALUE
);
1193 } else if (ext
&& !strcmpiW(ext
, cmdExt
)) {
1194 WCMD_batch (thisDir
, command
, called
, NULL
, INVALID_HANDLE_VALUE
);
1198 /* thisDir contains the file to be launched, but with what?
1199 eg. a.exe will require a.exe to be launched, a.html may be iexplore */
1200 hinst
= FindExecutableW (thisDir
, NULL
, temp
);
1201 if ((INT_PTR
)hinst
< 32)
1204 console
= SHGetFileInfoW(temp
, 0, &psfi
, sizeof(psfi
), SHGFI_EXETYPE
);
1206 ZeroMemory (&st
, sizeof(STARTUPINFOW
));
1207 st
.cb
= sizeof(STARTUPINFOW
);
1208 init_msvcrt_io_block(&st
);
1210 /* Launch the process and if a CUI wait on it to complete
1211 Note: Launching internal wine processes cannot specify a full path to exe */
1212 status
= CreateProcessW(assumeInternal
?NULL
: thisDir
,
1213 command
, NULL
, NULL
, TRUE
, 0, NULL
, NULL
, &st
, &pe
);
1214 if ((opt_c
|| opt_k
) && !opt_s
&& !status
1215 && GetLastError()==ERROR_FILE_NOT_FOUND
&& command
[0]=='\"') {
1216 /* strip first and last quote WCHARacters and try again */
1217 WCMD_opt_s_strip_quotes(command
);
1219 WCMD_run_program(command
, called
);
1226 if (!assumeInternal
&& !console
) errorlevel
= 0;
1229 /* Always wait when called in a batch program context */
1230 if (assumeInternal
|| context
|| !HIWORD(console
)) WaitForSingleObject (pe
.hProcess
, INFINITE
);
1231 GetExitCodeProcess (pe
.hProcess
, &errorlevel
);
1232 if (errorlevel
== STILL_ACTIVE
) errorlevel
= 0;
1234 CloseHandle(pe
.hProcess
);
1235 CloseHandle(pe
.hThread
);
1241 /* Not found anywhere - give up */
1242 SetLastError(ERROR_FILE_NOT_FOUND
);
1243 WCMD_print_error ();
1245 /* If a command fails to launch, it sets errorlevel 9009 - which
1246 does not seem to have any associated constant definition */
1252 /*****************************************************************************
1253 * Process one command. If the command is EXIT this routine does not return.
1254 * We will recurse through here executing batch files.
1256 void WCMD_execute (const WCHAR
*command
, const WCHAR
*redirects
,
1257 const WCHAR
*forVariable
, const WCHAR
*forValue
,
1260 WCHAR
*cmd
, *p
, *redir
;
1262 DWORD count
, creationDisposition
;
1265 SECURITY_ATTRIBUTES sa
;
1266 WCHAR
*new_cmd
= NULL
;
1267 WCHAR
*new_redir
= NULL
;
1268 HANDLE old_stdhandles
[3] = {GetStdHandle (STD_INPUT_HANDLE
),
1269 GetStdHandle (STD_OUTPUT_HANDLE
),
1270 GetStdHandle (STD_ERROR_HANDLE
)};
1271 DWORD idx_stdhandles
[3] = {STD_INPUT_HANDLE
,
1274 BOOL prev_echo_mode
, piped
= FALSE
;
1276 WINE_TRACE("command on entry:%s (%p), with forVariable '%s'='%s'\n",
1277 wine_dbgstr_w(command
), cmdList
,
1278 wine_dbgstr_w(forVariable
), wine_dbgstr_w(forValue
));
1280 /* If the next command is a pipe then we implement pipes by redirecting
1281 the output from this command to a temp file and input into the
1282 next command from that temp file.
1283 FIXME: Use of named pipes would make more sense here as currently this
1284 process has to finish before the next one can start but this requires
1285 a change to not wait for the first app to finish but rather the pipe */
1286 if (cmdList
&& (*cmdList
)->nextcommand
&&
1287 (*cmdList
)->nextcommand
->prevDelim
== CMD_PIPE
) {
1289 WCHAR temp_path
[MAX_PATH
];
1290 static const WCHAR cmdW
[] = {'C','M','D','\0'};
1292 /* Remember piping is in action */
1293 WINE_TRACE("Output needs to be piped\n");
1296 /* Generate a unique temporary filename */
1297 GetTempPathW(sizeof(temp_path
)/sizeof(WCHAR
), temp_path
);
1298 GetTempFileNameW(temp_path
, cmdW
, 0, (*cmdList
)->nextcommand
->pipeFile
);
1299 WINE_TRACE("Using temporary file of %s\n",
1300 wine_dbgstr_w((*cmdList
)->nextcommand
->pipeFile
));
1303 /* Move copy of the command onto the heap so it can be expanded */
1304 new_cmd
= HeapAlloc( GetProcessHeap(), 0, MAXSTRING
* sizeof(WCHAR
));
1307 WINE_ERR("Could not allocate memory for new_cmd\n");
1310 strcpyW(new_cmd
, command
);
1312 /* Move copy of the redirects onto the heap so it can be expanded */
1313 new_redir
= HeapAlloc( GetProcessHeap(), 0, MAXSTRING
* sizeof(WCHAR
));
1316 WINE_ERR("Could not allocate memory for new_redir\n");
1317 HeapFree( GetProcessHeap(), 0, new_cmd
);
1321 /* If piped output, send stdout to the pipe by appending >filename to redirects */
1323 static const WCHAR redirOut
[] = {'%','s',' ','>',' ','%','s','\0'};
1324 wsprintfW (new_redir
, redirOut
, redirects
, (*cmdList
)->nextcommand
->pipeFile
);
1325 WINE_TRACE("Redirects now %s\n", wine_dbgstr_w(new_redir
));
1327 strcpyW(new_redir
, redirects
);
1330 /* Expand variables in command line mode only (batch mode will
1331 be expanded as the line is read in, except for 'for' loops) */
1332 handleExpansion(new_cmd
, (context
!= NULL
), forVariable
, forValue
);
1333 handleExpansion(new_redir
, (context
!= NULL
), forVariable
, forValue
);
1337 * Changing default drive has to be handled as a special case.
1340 if ((cmd
[1] == ':') && IsCharAlphaW(cmd
[0]) && (strlenW(cmd
) == 2)) {
1342 WCHAR dir
[MAX_PATH
];
1344 /* According to MSDN CreateProcess docs, special env vars record
1345 the current directory on each drive, in the form =C:
1346 so see if one specified, and if so go back to it */
1347 strcpyW(envvar
, equalsW
);
1348 strcatW(envvar
, cmd
);
1349 if (GetEnvironmentVariableW(envvar
, dir
, MAX_PATH
) == 0) {
1350 static const WCHAR fmt
[] = {'%','s','\\','\0'};
1351 wsprintfW(cmd
, fmt
, cmd
);
1352 WINE_TRACE("No special directory settings, using dir of %s\n", wine_dbgstr_w(cmd
));
1354 WINE_TRACE("Got directory %s as %s\n", wine_dbgstr_w(envvar
), wine_dbgstr_w(cmd
));
1355 status
= SetCurrentDirectoryW(cmd
);
1356 if (!status
) WCMD_print_error ();
1357 HeapFree( GetProcessHeap(), 0, cmd
);
1358 HeapFree( GetProcessHeap(), 0, new_redir
);
1362 sa
.nLength
= sizeof(sa
);
1363 sa
.lpSecurityDescriptor
= NULL
;
1364 sa
.bInheritHandle
= TRUE
;
1367 * Redirect stdin, stdout and/or stderr if required.
1370 /* STDIN could come from a preceding pipe, so delete on close if it does */
1371 if (cmdList
&& (*cmdList
)->pipeFile
[0] != 0x00) {
1372 WINE_TRACE("Input coming from %s\n", wine_dbgstr_w((*cmdList
)->pipeFile
));
1373 h
= CreateFileW((*cmdList
)->pipeFile
, GENERIC_READ
,
1374 FILE_SHARE_READ
, &sa
, OPEN_EXISTING
,
1375 FILE_ATTRIBUTE_NORMAL
| FILE_FLAG_DELETE_ON_CLOSE
, NULL
);
1376 if (h
== INVALID_HANDLE_VALUE
) {
1377 WCMD_print_error ();
1378 HeapFree( GetProcessHeap(), 0, cmd
);
1379 HeapFree( GetProcessHeap(), 0, new_redir
);
1382 SetStdHandle (STD_INPUT_HANDLE
, h
);
1384 /* No need to remember the temporary name any longer once opened */
1385 (*cmdList
)->pipeFile
[0] = 0x00;
1387 /* Otherwise STDIN could come from a '<' redirect */
1388 } else if ((p
= strchrW(new_redir
,'<')) != NULL
) {
1389 h
= CreateFileW(WCMD_parameter(++p
, 0, NULL
, NULL
), GENERIC_READ
, FILE_SHARE_READ
,
1390 &sa
, OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, NULL
);
1391 if (h
== INVALID_HANDLE_VALUE
) {
1392 WCMD_print_error ();
1393 HeapFree( GetProcessHeap(), 0, cmd
);
1394 HeapFree( GetProcessHeap(), 0, new_redir
);
1397 SetStdHandle (STD_INPUT_HANDLE
, h
);
1400 /* Scan the whole command looking for > and 2> */
1402 while (redir
!= NULL
&& ((p
= strchrW(redir
,'>')) != NULL
)) {
1405 if (p
> redir
&& (*(p
-1)=='2'))
1412 creationDisposition
= OPEN_ALWAYS
;
1416 creationDisposition
= CREATE_ALWAYS
;
1419 /* Add support for 2>&1 */
1422 int idx
= *(p
+1) - '0';
1424 if (DuplicateHandle(GetCurrentProcess(),
1425 GetStdHandle(idx_stdhandles
[idx
]),
1426 GetCurrentProcess(),
1428 0, TRUE
, DUPLICATE_SAME_ACCESS
) == 0) {
1429 WINE_FIXME("Duplicating handle failed with gle %d\n", GetLastError());
1431 WINE_TRACE("Redirect %d (%p) to %d (%p)\n", handle
, GetStdHandle(idx_stdhandles
[idx
]), idx
, h
);
1434 WCHAR
*param
= WCMD_parameter(p
, 0, NULL
, NULL
);
1435 h
= CreateFileW(param
, GENERIC_WRITE
, 0, &sa
, creationDisposition
,
1436 FILE_ATTRIBUTE_NORMAL
, NULL
);
1437 if (h
== INVALID_HANDLE_VALUE
) {
1438 WCMD_print_error ();
1439 HeapFree( GetProcessHeap(), 0, cmd
);
1440 HeapFree( GetProcessHeap(), 0, new_redir
);
1443 if (SetFilePointer (h
, 0, NULL
, FILE_END
) ==
1444 INVALID_SET_FILE_POINTER
) {
1445 WCMD_print_error ();
1447 WINE_TRACE("Redirect %d to '%s' (%p)\n", handle
, wine_dbgstr_w(param
), h
);
1450 SetStdHandle (idx_stdhandles
[handle
], h
);
1454 * Strip leading whitespaces, and a '@' if supplied
1456 whichcmd
= WCMD_skip_leading_spaces(cmd
);
1457 WINE_TRACE("Command: '%s'\n", wine_dbgstr_w(cmd
));
1458 if (whichcmd
[0] == '@') whichcmd
++;
1461 * Check if the command entered is internal. If it is, pass the rest of the
1462 * line down to the command. If not try to run a program.
1466 while (IsCharAlphaNumericW(whichcmd
[count
])) {
1469 for (i
=0; i
<=WCMD_EXIT
; i
++) {
1470 if (CompareStringW(LOCALE_USER_DEFAULT
, NORM_IGNORECASE
| SORT_STRINGSORT
,
1471 whichcmd
, count
, inbuilt
[i
], -1) == CSTR_EQUAL
) break;
1473 p
= WCMD_skip_leading_spaces (&whichcmd
[count
]);
1474 WCMD_parse (p
, quals
, param1
, param2
);
1475 WINE_TRACE("param1: %s, param2: %s\n", wine_dbgstr_w(param1
), wine_dbgstr_w(param2
));
1477 if (i
<= WCMD_EXIT
&& (p
[0] == '/') && (p
[1] == '?')) {
1478 /* this is a help request for a builtin program */
1480 memcpy(p
, whichcmd
, count
* sizeof(WCHAR
));
1492 WCMD_setshow_default (p
);
1495 WCMD_clear_screen ();
1504 WCMD_setshow_date ();
1514 WCMD_echo(&whichcmd
[count
]);
1517 WCMD_for (p
, cmdList
);
1520 WCMD_goto (cmdList
);
1526 WCMD_if (p
, cmdList
);
1529 WCMD_volume (TRUE
, p
);
1533 WCMD_create_dir (p
);
1539 WCMD_setshow_path (p
);
1545 WCMD_setshow_prompt ();
1555 WCMD_remove_dir (p
);
1564 WCMD_setshow_env (p
);
1570 WCMD_setshow_time ();
1573 if (strlenW(&whichcmd
[count
]) > 0)
1574 WCMD_title(&whichcmd
[count
+1]);
1580 WCMD_output(newline
);
1587 WCMD_volume (FALSE
, p
);
1596 WCMD_assoc(p
, TRUE
);
1602 WCMD_assoc(p
, FALSE
);
1611 WCMD_exit (cmdList
);
1614 prev_echo_mode
= echo_mode
;
1615 WCMD_run_program (whichcmd
, 0);
1616 echo_mode
= prev_echo_mode
;
1618 HeapFree( GetProcessHeap(), 0, cmd
);
1619 HeapFree( GetProcessHeap(), 0, new_redir
);
1621 /* Restore old handles */
1622 for (i
=0; i
<3; i
++) {
1623 if (old_stdhandles
[i
] != GetStdHandle(idx_stdhandles
[i
])) {
1624 CloseHandle (GetStdHandle (idx_stdhandles
[i
]));
1625 SetStdHandle (idx_stdhandles
[i
], old_stdhandles
[i
]);
1630 /*************************************************************************
1632 * Load a string from the resource file, handling any error
1633 * Returns string retrieved from resource file
1635 WCHAR
*WCMD_LoadMessage(UINT id
) {
1636 static WCHAR msg
[2048];
1637 static const WCHAR failedMsg
[] = {'F','a','i','l','e','d','!','\0'};
1639 if (!LoadStringW(GetModuleHandleW(NULL
), id
, msg
, sizeof(msg
)/sizeof(WCHAR
))) {
1640 WINE_FIXME("LoadString failed with %d\n", GetLastError());
1641 strcpyW(msg
, failedMsg
);
1646 /***************************************************************************
1649 * Dumps out the parsed command line to ensure syntax is correct
1651 static void WCMD_DumpCommands(CMD_LIST
*commands
) {
1652 CMD_LIST
*thisCmd
= commands
;
1654 WINE_TRACE("Parsed line:\n");
1655 while (thisCmd
!= NULL
) {
1656 WINE_TRACE("%p %d %2.2d %p %s Redir:%s\n",
1659 thisCmd
->bracketDepth
,
1660 thisCmd
->nextcommand
,
1661 wine_dbgstr_w(thisCmd
->command
),
1662 wine_dbgstr_w(thisCmd
->redirects
));
1663 thisCmd
= thisCmd
->nextcommand
;
1667 /***************************************************************************
1670 * Adds a command to the current command list
1672 static void WCMD_addCommand(WCHAR
*command
, int *commandLen
,
1673 WCHAR
*redirs
, int *redirLen
,
1674 WCHAR
**copyTo
, int **copyToLen
,
1675 CMD_DELIMITERS prevDelim
, int curDepth
,
1676 CMD_LIST
**lastEntry
, CMD_LIST
**output
) {
1678 CMD_LIST
*thisEntry
= NULL
;
1680 /* Allocate storage for command */
1681 thisEntry
= HeapAlloc(GetProcessHeap(), 0, sizeof(CMD_LIST
));
1683 /* Copy in the command */
1685 thisEntry
->command
= HeapAlloc(GetProcessHeap(), 0,
1686 (*commandLen
+1) * sizeof(WCHAR
));
1687 memcpy(thisEntry
->command
, command
, *commandLen
* sizeof(WCHAR
));
1688 thisEntry
->command
[*commandLen
] = 0x00;
1690 /* Copy in the redirects */
1691 thisEntry
->redirects
= HeapAlloc(GetProcessHeap(), 0,
1692 (*redirLen
+1) * sizeof(WCHAR
));
1693 memcpy(thisEntry
->redirects
, redirs
, *redirLen
* sizeof(WCHAR
));
1694 thisEntry
->redirects
[*redirLen
] = 0x00;
1695 thisEntry
->pipeFile
[0] = 0x00;
1697 /* Reset the lengths */
1700 *copyToLen
= commandLen
;
1704 thisEntry
->command
= NULL
;
1705 thisEntry
->redirects
= NULL
;
1706 thisEntry
->pipeFile
[0] = 0x00;
1709 /* Fill in other fields */
1710 thisEntry
->nextcommand
= NULL
;
1711 thisEntry
->prevDelim
= prevDelim
;
1712 thisEntry
->bracketDepth
= curDepth
;
1714 (*lastEntry
)->nextcommand
= thisEntry
;
1716 *output
= thisEntry
;
1718 *lastEntry
= thisEntry
;
1722 /***************************************************************************
1725 * Checks if the quote pointed to is the end-quote.
1729 * 1) The current parameter ends at EOL or at the beginning
1730 * of a redirection or pipe and not in a quote section.
1732 * 2) If the next character is a space and not in a quote section.
1734 * Returns TRUE if this is an end quote, and FALSE if it is not.
1737 static BOOL
WCMD_IsEndQuote(const WCHAR
*quote
, int quoteIndex
)
1739 int quoteCount
= quoteIndex
;
1742 /* If we are not in a quoted section, then we are not an end-quote */
1748 /* Check how many quotes are left for this parameter */
1749 for(i
=0;quote
[i
];i
++)
1756 /* Quote counting ends at EOL, redirection, space or pipe if current quote is complete */
1757 else if(((quoteCount
% 2) == 0)
1758 && ((quote
[i
] == '<') || (quote
[i
] == '>') || (quote
[i
] == '|') || (quote
[i
] == ' ')))
1764 /* If the quote is part of the last part of a series of quotes-on-quotes, then it must
1766 if(quoteIndex
>= (quoteCount
/ 2))
1775 /***************************************************************************
1776 * WCMD_ReadAndParseLine
1778 * Either uses supplied input or
1779 * Reads a file from the handle, and then...
1780 * Parse the text buffer, splitting into separate commands
1781 * - unquoted && strings split 2 commands but the 2nd is flagged as
1783 * - ( as the first character just ups the bracket depth
1784 * - unquoted ) when bracket depth > 0 terminates a bracket and
1785 * adds a CMD_LIST structure with null command
1786 * - Anything else gets put into the command string (including
1789 WCHAR
*WCMD_ReadAndParseLine(const WCHAR
*optionalcmd
, CMD_LIST
**output
, HANDLE readFrom
) {
1793 WCHAR curString
[MAXSTRING
];
1794 int curStringLen
= 0;
1795 WCHAR curRedirs
[MAXSTRING
];
1796 int curRedirsLen
= 0;
1800 CMD_LIST
*lastEntry
= NULL
;
1801 CMD_DELIMITERS prevDelim
= CMD_NONE
;
1802 static WCHAR
*extraSpace
= NULL
; /* Deliberately never freed */
1803 static const WCHAR remCmd
[] = {'r','e','m'};
1804 static const WCHAR forCmd
[] = {'f','o','r'};
1805 static const WCHAR ifCmd
[] = {'i','f'};
1806 static const WCHAR ifElse
[] = {'e','l','s','e'};
1812 BOOL onlyWhiteSpace
= FALSE
;
1813 BOOL lastWasWhiteSpace
= FALSE
;
1814 BOOL lastWasDo
= FALSE
;
1815 BOOL lastWasIn
= FALSE
;
1816 BOOL lastWasElse
= FALSE
;
1817 BOOL lastWasRedirect
= TRUE
;
1819 /* Allocate working space for a command read from keyboard, file etc */
1821 extraSpace
= HeapAlloc(GetProcessHeap(), 0, (MAXSTRING
+1) * sizeof(WCHAR
));
1824 WINE_ERR("Could not allocate memory for extraSpace\n");
1828 /* If initial command read in, use that, otherwise get input from handle */
1829 if (optionalcmd
!= NULL
) {
1830 strcpyW(extraSpace
, optionalcmd
);
1831 } else if (readFrom
== INVALID_HANDLE_VALUE
) {
1832 WINE_FIXME("No command nor handle supplied\n");
1834 if (WCMD_fgets(extraSpace
, MAXSTRING
, readFrom
) == NULL
) return NULL
;
1836 curPos
= extraSpace
;
1838 /* Handle truncated input - issue warning */
1839 if (strlenW(extraSpace
) == MAXSTRING
-1) {
1840 WCMD_output_asis(WCMD_LoadMessage(WCMD_TRUNCATEDLINE
));
1841 WCMD_output_asis(extraSpace
);
1842 WCMD_output_asis(newline
);
1845 /* Replace env vars if in a batch context */
1846 if (context
) handleExpansion(extraSpace
, FALSE
, NULL
, NULL
);
1847 /* Show prompt before batch line IF echo is on and in batch program */
1848 if (context
&& echo_mode
&& extraSpace
[0] && (extraSpace
[0] != '@')) {
1849 static const WCHAR spc
[]={' ','\0'};
1850 static const WCHAR echoDot
[] = {'e','c','h','o','.'};
1851 static const WCHAR echoCol
[] = {'e','c','h','o',':'};
1852 const DWORD len
= sizeof(echoDot
)/sizeof(echoDot
[0]);
1853 DWORD curr_size
= strlenW(extraSpace
);
1854 DWORD min_len
= (curr_size
< len
? curr_size
: len
);
1856 WCMD_output_asis(extraSpace
);
1857 /* I don't know why Windows puts a space here but it does */
1858 /* Except for lines starting with 'echo.' or 'echo:'. Ask MS why */
1859 if (CompareStringW(LOCALE_SYSTEM_DEFAULT
, NORM_IGNORECASE
,
1860 extraSpace
, min_len
, echoDot
, len
) != CSTR_EQUAL
1861 && CompareStringW(LOCALE_SYSTEM_DEFAULT
, NORM_IGNORECASE
,
1862 extraSpace
, min_len
, echoCol
, len
) != CSTR_EQUAL
)
1864 WCMD_output_asis(spc
);
1866 WCMD_output_asis(newline
);
1869 /* Start with an empty string, copying to the command string */
1872 curCopyTo
= curString
;
1873 curLen
= &curStringLen
;
1874 lastWasRedirect
= FALSE
; /* Required for eg spaces between > and filename */
1876 /* Parse every character on the line being processed */
1877 while (*curPos
!= 0x00) {
1882 WINE_TRACE("Looking at '%c' (len:%d, lws:%d, ows:%d)\n", *curPos, *curLen,
1883 lastWasWhiteSpace, onlyWhiteSpace);
1886 /* Certain commands need special handling */
1887 if (curStringLen
== 0 && curCopyTo
== curString
) {
1888 static const WCHAR forDO
[] = {'d','o'};
1890 /* If command starts with 'rem ', ignore any &&, ( etc. */
1891 if (WCMD_keyword_ws_found(remCmd
, sizeof(remCmd
)/sizeof(remCmd
[0]), curPos
)) {
1894 } else if (WCMD_keyword_ws_found(forCmd
, sizeof(forCmd
)/sizeof(forCmd
[0]), curPos
)) {
1897 /* If command starts with 'if ' or 'else ', handle ('s mid line. We should ensure this
1898 is only true in the command portion of the IF statement, but this
1899 should suffice for now
1900 FIXME: Silly syntax like "if 1(==1( (
1902 )" will be parsed wrong */
1903 } else if (WCMD_keyword_ws_found(ifCmd
, sizeof(ifCmd
)/sizeof(ifCmd
[0]), curPos
)) {
1906 } else if (WCMD_keyword_ws_found(ifElse
, sizeof(ifElse
)/sizeof(ifElse
[0]), curPos
)) {
1907 const int keyw_len
= sizeof(ifElse
)/sizeof(ifElse
[0]) + 1;
1910 onlyWhiteSpace
= TRUE
;
1911 memcpy(&curCopyTo
[*curLen
], curPos
, keyw_len
*sizeof(WCHAR
));
1912 (*curLen
)+=keyw_len
;
1916 /* In a for loop, the DO command will follow a close bracket followed by
1917 whitespace, followed by DO, ie closeBracket inserts a NULL entry, curLen
1918 is then 0, and all whitespace is skipped */
1920 WCMD_keyword_ws_found(forDO
, sizeof(forDO
)/sizeof(forDO
[0]), curPos
)) {
1921 const int keyw_len
= sizeof(forDO
)/sizeof(forDO
[0]) + 1;
1922 WINE_TRACE("Found 'DO '\n");
1924 onlyWhiteSpace
= TRUE
;
1925 memcpy(&curCopyTo
[*curLen
], curPos
, keyw_len
*sizeof(WCHAR
));
1926 (*curLen
)+=keyw_len
;
1930 } else if (curCopyTo
== curString
) {
1932 /* Special handling for the 'FOR' command */
1933 if (inFor
&& lastWasWhiteSpace
) {
1934 static const WCHAR forIN
[] = {'i','n'};
1936 WINE_TRACE("Found 'FOR ', comparing next parm: '%s'\n", wine_dbgstr_w(curPos
));
1938 if (WCMD_keyword_ws_found(forIN
, sizeof(forIN
)/sizeof(forIN
[0]), curPos
)) {
1939 const int keyw_len
= sizeof(forIN
)/sizeof(forIN
[0]) + 1;
1940 WINE_TRACE("Found 'IN '\n");
1942 onlyWhiteSpace
= TRUE
;
1943 memcpy(&curCopyTo
[*curLen
], curPos
, keyw_len
*sizeof(WCHAR
));
1944 (*curLen
)+=keyw_len
;
1951 /* Nothing 'ends' a REM statement and &&, quotes etc are ineffective,
1952 so just use the default processing ie skip character specific
1954 if (!inRem
) thisChar
= *curPos
;
1955 else thisChar
= 'X'; /* Character with no special processing */
1957 lastWasWhiteSpace
= FALSE
; /* Will be reset below */
1961 case '=': /* drop through - ignore token delimiters at the start of a command */
1962 case ',': /* drop through - ignore token delimiters at the start of a command */
1963 case '\t':/* drop through - ignore token delimiters at the start of a command */
1965 /* If a redirect in place, it ends here */
1966 if (!inQuotes
&& !lastWasRedirect
) {
1968 /* If finishing off a redirect, add a whitespace delimiter */
1969 if (curCopyTo
== curRedirs
) {
1970 curCopyTo
[(*curLen
)++] = ' ';
1972 curCopyTo
= curString
;
1973 curLen
= &curStringLen
;
1976 curCopyTo
[(*curLen
)++] = *curPos
;
1979 /* Remember just processed whitespace */
1980 lastWasWhiteSpace
= TRUE
;
1984 case '>': /* drop through - handle redirect chars the same */
1986 /* Make a redirect start here */
1988 curCopyTo
= curRedirs
;
1989 curLen
= &curRedirsLen
;
1990 lastWasRedirect
= TRUE
;
1993 /* See if 1>, 2> etc, in which case we have some patching up
1994 to do (provided there's a preceding whitespace, and enough
1995 chars read so far) */
1996 if (curStringLen
> 2
1997 && (*(curPos
-1)>='1') && (*(curPos
-1)<='9')
1998 && ((*(curPos
-2)==' ') || (*(curPos
-2)=='\t'))) {
2000 curString
[curStringLen
] = 0x00;
2001 curCopyTo
[(*curLen
)++] = *(curPos
-1);
2004 curCopyTo
[(*curLen
)++] = *curPos
;
2006 /* If a redirect is immediately followed by '&' (ie. 2>&1) then
2007 do not process that ampersand as an AND operator */
2008 if (thisChar
== '>' && *(curPos
+1) == '&') {
2009 curCopyTo
[(*curLen
)++] = *(curPos
+1);
2014 case '|': /* Pipe character only if not || */
2016 lastWasRedirect
= FALSE
;
2018 /* Add an entry to the command list */
2019 if (curStringLen
> 0) {
2021 /* Add the current command */
2022 WCMD_addCommand(curString
, &curStringLen
,
2023 curRedirs
, &curRedirsLen
,
2024 &curCopyTo
, &curLen
,
2025 prevDelim
, curDepth
,
2026 &lastEntry
, output
);
2030 if (*(curPos
+1) == '|') {
2031 curPos
++; /* Skip other | */
2032 prevDelim
= CMD_ONFAILURE
;
2034 prevDelim
= CMD_PIPE
;
2037 curCopyTo
[(*curLen
)++] = *curPos
;
2041 case '"': if (WCMD_IsEndQuote(curPos
, inQuotes
)) {
2044 inQuotes
++; /* Quotes within quotes are fun! */
2046 curCopyTo
[(*curLen
)++] = *curPos
;
2047 lastWasRedirect
= FALSE
;
2050 case '(': /* If a '(' is the first non whitespace in a command portion
2051 ie start of line or just after &&, then we read until an
2052 unquoted ) is found */
2053 WINE_TRACE("Found '(' conditions: curLen(%d), inQ(%d), onlyWS(%d)"
2054 ", for(%d, In:%d, Do:%d)"
2055 ", if(%d, else:%d, lwe:%d)\n",
2058 inFor
, lastWasIn
, lastWasDo
,
2059 inIf
, inElse
, lastWasElse
);
2060 lastWasRedirect
= FALSE
;
2062 /* Ignore open brackets inside the for set */
2063 if (*curLen
== 0 && !inIn
) {
2066 /* If in quotes, ignore brackets */
2067 } else if (inQuotes
) {
2068 curCopyTo
[(*curLen
)++] = *curPos
;
2070 /* In a FOR loop, an unquoted '(' may occur straight after
2072 In an IF statement just handle it regardless as we don't
2074 In an ELSE statement, only allow it straight away after
2075 the ELSE and whitespace
2078 (inElse
&& lastWasElse
&& onlyWhiteSpace
) ||
2079 (inFor
&& (lastWasIn
|| lastWasDo
) && onlyWhiteSpace
)) {
2081 /* If entering into an 'IN', set inIn */
2082 if (inFor
&& lastWasIn
&& onlyWhiteSpace
) {
2083 WINE_TRACE("Inside an IN\n");
2087 /* Add the current command */
2088 WCMD_addCommand(curString
, &curStringLen
,
2089 curRedirs
, &curRedirsLen
,
2090 &curCopyTo
, &curLen
,
2091 prevDelim
, curDepth
,
2092 &lastEntry
, output
);
2096 curCopyTo
[(*curLen
)++] = *curPos
;
2100 case '&': if (!inQuotes
) {
2101 lastWasRedirect
= FALSE
;
2103 /* Add an entry to the command list */
2104 if (curStringLen
> 0) {
2106 /* Add the current command */
2107 WCMD_addCommand(curString
, &curStringLen
,
2108 curRedirs
, &curRedirsLen
,
2109 &curCopyTo
, &curLen
,
2110 prevDelim
, curDepth
,
2111 &lastEntry
, output
);
2115 if (*(curPos
+1) == '&') {
2116 curPos
++; /* Skip other & */
2117 prevDelim
= CMD_ONSUCCESS
;
2119 prevDelim
= CMD_NONE
;
2122 curCopyTo
[(*curLen
)++] = *curPos
;
2126 case ')': if (!inQuotes
&& curDepth
> 0) {
2127 lastWasRedirect
= FALSE
;
2129 /* Add the current command if there is one */
2132 /* Add the current command */
2133 WCMD_addCommand(curString
, &curStringLen
,
2134 curRedirs
, &curRedirsLen
,
2135 &curCopyTo
, &curLen
,
2136 prevDelim
, curDepth
,
2137 &lastEntry
, output
);
2140 /* Add an empty entry to the command list */
2141 prevDelim
= CMD_NONE
;
2142 WCMD_addCommand(NULL
, &curStringLen
,
2143 curRedirs
, &curRedirsLen
,
2144 &curCopyTo
, &curLen
,
2145 prevDelim
, curDepth
,
2146 &lastEntry
, output
);
2149 /* Leave inIn if necessary */
2150 if (inIn
) inIn
= FALSE
;
2152 curCopyTo
[(*curLen
)++] = *curPos
;
2156 lastWasRedirect
= FALSE
;
2157 curCopyTo
[(*curLen
)++] = *curPos
;
2162 /* At various times we need to know if we have only skipped whitespace,
2163 so reset this variable and then it will remain true until a non
2164 whitespace is found */
2165 if ((thisChar
!= ' ') && (thisChar
!= '\t') && (thisChar
!= '\n'))
2166 onlyWhiteSpace
= FALSE
;
2168 /* Flag end of interest in FOR DO and IN parms once something has been processed */
2169 if (!lastWasWhiteSpace
) {
2170 lastWasIn
= lastWasDo
= FALSE
;
2173 /* If we have reached the end, add this command into the list */
2174 if (*curPos
== 0x00 && *curLen
> 0) {
2176 /* Add an entry to the command list */
2177 WCMD_addCommand(curString
, &curStringLen
,
2178 curRedirs
, &curRedirsLen
,
2179 &curCopyTo
, &curLen
,
2180 prevDelim
, curDepth
,
2181 &lastEntry
, output
);
2184 /* If we have reached the end of the string, see if bracketing outstanding */
2185 if (*curPos
== 0x00 && curDepth
> 0 && readFrom
!= INVALID_HANDLE_VALUE
) {
2187 prevDelim
= CMD_NONE
;
2189 memset(extraSpace
, 0x00, (MAXSTRING
+1) * sizeof(WCHAR
));
2191 /* Read more, skipping any blank lines */
2192 while (*extraSpace
== 0x00) {
2193 if (!context
) WCMD_output_asis( WCMD_LoadMessage(WCMD_MOREPROMPT
));
2194 if (WCMD_fgets(extraSpace
, MAXSTRING
, readFrom
) == NULL
) break;
2196 curPos
= extraSpace
;
2197 if (context
) handleExpansion(extraSpace
, FALSE
, NULL
, NULL
);
2198 /* Continue to echo commands IF echo is on and in batch program */
2199 if (context
&& echo_mode
&& extraSpace
[0] && (extraSpace
[0] != '@')) {
2200 WCMD_output_asis(extraSpace
);
2201 WCMD_output_asis(newline
);
2206 /* Dump out the parsed output */
2207 WCMD_DumpCommands(*output
);
2212 /***************************************************************************
2213 * WCMD_process_commands
2215 * Process all the commands read in so far
2217 CMD_LIST
*WCMD_process_commands(CMD_LIST
*thisCmd
, BOOL oneBracket
,
2218 const WCHAR
*var
, const WCHAR
*val
) {
2222 if (thisCmd
&& oneBracket
) bdepth
= thisCmd
->bracketDepth
;
2224 /* Loop through the commands, processing them one by one */
2227 CMD_LIST
*origCmd
= thisCmd
;
2229 /* If processing one bracket only, and we find the end bracket
2230 entry (or less), return */
2231 if (oneBracket
&& !thisCmd
->command
&&
2232 bdepth
<= thisCmd
->bracketDepth
) {
2233 WINE_TRACE("Finished bracket @ %p, next command is %p\n",
2234 thisCmd
, thisCmd
->nextcommand
);
2235 return thisCmd
->nextcommand
;
2238 /* Ignore the NULL entries a ')' inserts (Only 'if' cares
2239 about them and it will be handled in there)
2240 Also, skip over any batch labels (eg. :fred) */
2241 if (thisCmd
->command
&& thisCmd
->command
[0] != ':') {
2242 WINE_TRACE("Executing command: '%s'\n", wine_dbgstr_w(thisCmd
->command
));
2243 WCMD_execute (thisCmd
->command
, thisCmd
->redirects
, var
, val
, &thisCmd
);
2246 /* Step on unless the command itself already stepped on */
2247 if (thisCmd
== origCmd
) thisCmd
= thisCmd
->nextcommand
;
2252 /***************************************************************************
2253 * WCMD_free_commands
2255 * Frees the storage held for a parsed command line
2256 * - This is not done in the process_commands, as eventually the current
2257 * pointer will be modified within the commands, and hence a single free
2258 * routine is simpler
2260 void WCMD_free_commands(CMD_LIST
*cmds
) {
2262 /* Loop through the commands, freeing them one by one */
2264 CMD_LIST
*thisCmd
= cmds
;
2265 cmds
= cmds
->nextcommand
;
2266 HeapFree(GetProcessHeap(), 0, thisCmd
->command
);
2267 HeapFree(GetProcessHeap(), 0, thisCmd
->redirects
);
2268 HeapFree(GetProcessHeap(), 0, thisCmd
);
2273 /*****************************************************************************
2274 * Main entry point. This is a console application so we have a main() not a
2278 int wmain (int argc
, WCHAR
*argvW
[])
2286 static const WCHAR promptW
[] = {'P','R','O','M','P','T','\0'};
2287 static const WCHAR defaultpromptW
[] = {'$','P','$','G','\0'};
2288 char ansiVersion
[100];
2289 CMD_LIST
*toExecute
= NULL
; /* Commands left to be executed */
2293 /* Pre initialize some messages */
2294 strcpy(ansiVersion
, PACKAGE_VERSION
);
2295 MultiByteToWideChar(CP_ACP
, 0, ansiVersion
, -1, string
, 1024);
2296 wsprintfW(version_string
, WCMD_LoadMessage(WCMD_VERSION
), string
);
2297 strcpyW(anykey
, WCMD_LoadMessage(WCMD_ANYKEY
));
2300 opt_c
=opt_k
=opt_q
=opt_s
=0;
2304 WINE_TRACE("Command line parm: '%s'\n", wine_dbgstr_w(*argvW
));
2305 if ((*argvW
)[0]!='/' || (*argvW
)[1]=='\0') {
2312 if (tolowerW(c
)=='c') {
2314 } else if (tolowerW(c
)=='q') {
2316 } else if (tolowerW(c
)=='k') {
2318 } else if (tolowerW(c
)=='s') {
2320 } else if (tolowerW(c
)=='a') {
2322 } else if (tolowerW(c
)=='u') {
2324 } else if (tolowerW(c
)=='t' && (*argvW
)[2]==':') {
2325 opt_t
=strtoulW(&(*argvW
)[3], NULL
, 16);
2326 } else if (tolowerW(c
)=='x' || tolowerW(c
)=='y') {
2327 /* Ignored for compatibility with Windows */
2330 if ((*argvW
)[2]==0) {
2334 else /* handle `cmd /cnotepad.exe` and `cmd /x/c ...` */
2339 if (opt_c
|| opt_k
) /* break out of parsing immediately after c or k */
2344 static const WCHAR eoff
[] = {'O','F','F','\0'};
2348 if (opt_c
|| opt_k
) {
2354 /* opt_s left unflagged if the command starts with and contains exactly
2355 * one quoted string (exactly two quote characters). The quoted string
2356 * must be an executable name that has whitespace and must not have the
2357 * following characters: &<>()@^| */
2359 /* Build the command to execute */
2363 for (arg
= argvW
; argsLeft
>0; arg
++,argsLeft
--)
2365 int has_space
,bcount
;
2371 if( !*a
) has_space
=1;
2376 if (*a
==' ' || *a
=='\t') {
2378 } else if (*a
=='"') {
2379 /* doubling of '\' preceding a '"',
2380 * plus escaping of said '"'
2389 len
+=(a
-*arg
) + 1; /* for the separating space */
2392 len
+=2; /* for the quotes */
2400 /* check argvW[0] for a space and invalid characters */
2405 if (*p
=='&' || *p
=='<' || *p
=='>' || *p
=='(' || *p
==')'
2406 || *p
=='@' || *p
=='^' || *p
=='|') {
2416 cmd
= HeapAlloc(GetProcessHeap(), 0, len
* sizeof(WCHAR
));
2422 for (arg
= argvW
; argsLeft
>0; arg
++,argsLeft
--)
2424 int has_space
,has_quote
;
2427 /* Check for quotes and spaces in this argument */
2428 has_space
=has_quote
=0;
2430 if( !*a
) has_space
=1;
2432 if (*a
==' ' || *a
=='\t') {
2436 } else if (*a
=='"') {
2444 /* Now transfer it to the command line */
2461 /* Double all the '\\' preceding this '"', plus one */
2462 for (i
=0;i
<=bcount
;i
++)
2481 p
--; /* remove last space */
2484 WINE_TRACE("/c command line: '%s'\n", wine_dbgstr_w(cmd
));
2486 /* strip first and last quote characters if opt_s; check for invalid
2487 * executable is done later */
2488 if (opt_s
&& *cmd
=='\"')
2489 WCMD_opt_s_strip_quotes(cmd
);
2493 /* If we do a "cmd /c command", we don't want to allocate a new
2494 * console since the command returns immediately. Rather, we use
2495 * the currently allocated input and output handles. This allows
2496 * us to pipe to and read from the command interpreter.
2499 /* Parse the command string, without reading any more input */
2500 WCMD_ReadAndParseLine(cmd
, &toExecute
, INVALID_HANDLE_VALUE
);
2501 WCMD_process_commands(toExecute
, FALSE
, NULL
, NULL
);
2502 WCMD_free_commands(toExecute
);
2505 HeapFree(GetProcessHeap(), 0, cmd
);
2509 SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE
), ENABLE_LINE_INPUT
|
2510 ENABLE_ECHO_INPUT
| ENABLE_PROCESSED_INPUT
);
2511 SetConsoleTitleW(WCMD_LoadMessage(WCMD_CONSTITLE
));
2513 /* Note: cmd.exe /c dir does not get a new color, /k dir does */
2515 if (!(((opt_t
& 0xF0) >> 4) == (opt_t
& 0x0F))) {
2516 defaultColor
= opt_t
& 0xFF;
2521 /* Check HKCU\Software\Microsoft\Command Processor
2522 Then HKLM\Software\Microsoft\Command Processor
2523 for defaultcolour value
2524 Note Can be supplied as DWORD or REG_SZ
2525 Note2 When supplied as REG_SZ it's in decimal!!! */
2528 DWORD value
=0, size
=4;
2529 static const WCHAR regKeyW
[] = {'S','o','f','t','w','a','r','e','\\',
2530 'M','i','c','r','o','s','o','f','t','\\',
2531 'C','o','m','m','a','n','d',' ','P','r','o','c','e','s','s','o','r','\0'};
2532 static const WCHAR dfltColorW
[] = {'D','e','f','a','u','l','t','C','o','l','o','r','\0'};
2534 if (RegOpenKeyExW(HKEY_CURRENT_USER
, regKeyW
,
2535 0, KEY_READ
, &key
) == ERROR_SUCCESS
) {
2538 /* See if DWORD or REG_SZ */
2539 if (RegQueryValueExW(key
, dfltColorW
, NULL
, &type
,
2540 NULL
, NULL
) == ERROR_SUCCESS
) {
2541 if (type
== REG_DWORD
) {
2542 size
= sizeof(DWORD
);
2543 RegQueryValueExW(key
, dfltColorW
, NULL
, NULL
,
2544 (LPBYTE
)&value
, &size
);
2545 } else if (type
== REG_SZ
) {
2546 size
= sizeof(strvalue
)/sizeof(WCHAR
);
2547 RegQueryValueExW(key
, dfltColorW
, NULL
, NULL
,
2548 (LPBYTE
)strvalue
, &size
);
2549 value
= strtoulW(strvalue
, NULL
, 10);
2555 if (value
== 0 && RegOpenKeyExW(HKEY_LOCAL_MACHINE
, regKeyW
,
2556 0, KEY_READ
, &key
) == ERROR_SUCCESS
) {
2559 /* See if DWORD or REG_SZ */
2560 if (RegQueryValueExW(key
, dfltColorW
, NULL
, &type
,
2561 NULL
, NULL
) == ERROR_SUCCESS
) {
2562 if (type
== REG_DWORD
) {
2563 size
= sizeof(DWORD
);
2564 RegQueryValueExW(key
, dfltColorW
, NULL
, NULL
,
2565 (LPBYTE
)&value
, &size
);
2566 } else if (type
== REG_SZ
) {
2567 size
= sizeof(strvalue
)/sizeof(WCHAR
);
2568 RegQueryValueExW(key
, dfltColorW
, NULL
, NULL
,
2569 (LPBYTE
)strvalue
, &size
);
2570 value
= strtoulW(strvalue
, NULL
, 10);
2576 /* If one found, set the screen to that colour */
2577 if (!(((value
& 0xF0) >> 4) == (value
& 0x0F))) {
2578 defaultColor
= value
& 0xFF;
2585 /* Save cwd into appropriate env var */
2586 GetCurrentDirectoryW(1024, string
);
2587 if (IsCharAlphaW(string
[0]) && string
[1] == ':') {
2588 static const WCHAR fmt
[] = {'=','%','c',':','\0'};
2589 wsprintfW(envvar
, fmt
, string
[0]);
2590 SetEnvironmentVariableW(envvar
, string
);
2591 WINE_TRACE("Set %s to %s\n", wine_dbgstr_w(envvar
), wine_dbgstr_w(string
));
2595 /* Parse the command string, without reading any more input */
2596 WCMD_ReadAndParseLine(cmd
, &toExecute
, INVALID_HANDLE_VALUE
);
2597 WCMD_process_commands(toExecute
, FALSE
, NULL
, NULL
);
2598 WCMD_free_commands(toExecute
);
2600 HeapFree(GetProcessHeap(), 0, cmd
);
2604 * Loop forever getting commands and executing them.
2607 SetEnvironmentVariableW(promptW
, defaultpromptW
);
2611 /* Read until EOF (which for std input is never, but if redirect
2612 in place, may occur */
2613 if (echo_mode
) WCMD_show_prompt();
2614 if (WCMD_ReadAndParseLine(NULL
, &toExecute
,
2615 GetStdHandle(STD_INPUT_HANDLE
)) == NULL
)
2617 WCMD_process_commands(toExecute
, FALSE
, NULL
, NULL
);
2618 WCMD_free_commands(toExecute
);