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 in WCMD_output\n" );
178 ret
= (sizeof(string
)/sizeof(WCHAR
)) - 1;
182 WCMD_output_asis_len(string
, ret
, GetStdHandle(STD_OUTPUT_HANDLE
));
186 static int line_count
;
187 static int max_height
;
188 static int max_width
;
189 static BOOL paged_mode
;
192 void WCMD_enter_paged_mode(const WCHAR
*msg
)
194 CONSOLE_SCREEN_BUFFER_INFO consoleInfo
;
196 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE
), &consoleInfo
)) {
197 max_height
= consoleInfo
.dwSize
.Y
;
198 max_width
= consoleInfo
.dwSize
.X
;
206 pagedMessage
= (msg
==NULL
)? anykey
: msg
;
209 void WCMD_leave_paged_mode(void)
215 /***************************************************************************
218 * Read characters in from a console/file, returning result in Unicode
219 * with signature identical to ReadFile
221 BOOL
WCMD_ReadFile(const HANDLE hIn
, WCHAR
*intoBuf
, const DWORD maxChars
,
222 LPDWORD charsRead
, const LPOVERLAPPED unused
) {
226 /* Try to read from console as Unicode */
227 res
= ReadConsoleW(hIn
, intoBuf
, maxChars
, charsRead
, NULL
);
229 /* If reading from console has failed we assume its file
230 i/o so read in and convert from OEM codepage */
236 if (!(buffer
= get_file_buffer()))
239 /* Read from file (assume OEM codepage) */
240 res
= ReadFile(hIn
, buffer
, maxChars
, &numRead
, unused
);
242 /* Convert from OEM */
243 *charsRead
= MultiByteToWideChar(GetConsoleCP(), 0, buffer
, numRead
,
250 /*******************************************************************
251 * WCMD_output_asis_handle
253 * Send output to specified handle without formatting e.g. when message contains '%'
255 static void WCMD_output_asis_handle (DWORD std_handle
, const WCHAR
*message
) {
259 HANDLE handle
= GetStdHandle(std_handle
);
264 while (*ptr
&& *ptr
!='\n' && (numChars
< max_width
)) {
268 if (*ptr
== '\n') ptr
++;
269 WCMD_output_asis_len(message
, (ptr
) ? ptr
- message
: strlenW(message
), handle
);
272 if (++line_count
>= max_height
- 1) {
274 WCMD_output_asis_len(pagedMessage
, strlenW(pagedMessage
), handle
);
275 WCMD_ReadFile (GetStdHandle(STD_INPUT_HANDLE
), string
,
276 sizeof(string
)/sizeof(WCHAR
), &count
, NULL
);
279 } while (((message
= ptr
) != NULL
) && (*ptr
));
281 WCMD_output_asis_len(message
, lstrlenW(message
), handle
);
285 /*******************************************************************
288 * Send output to current standard output device, without formatting
289 * e.g. when message contains '%'
291 void WCMD_output_asis (const WCHAR
*message
) {
292 WCMD_output_asis_handle(STD_OUTPUT_HANDLE
, message
);
295 /*******************************************************************
296 * WCMD_output_asis_stderr
298 * Send output to current standard error device, without formatting
299 * e.g. when message contains '%'
301 void WCMD_output_asis_stderr (const WCHAR
*message
) {
302 WCMD_output_asis_handle(STD_ERROR_HANDLE
, message
);
305 /****************************************************************************
308 * Print the message for GetLastError
311 void WCMD_print_error (void) {
316 error_code
= GetLastError ();
317 status
= FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
,
318 NULL
, error_code
, 0, (LPWSTR
) &lpMsgBuf
, 0, NULL
);
320 WINE_FIXME ("Cannot display message for error %d, status %d\n",
321 error_code
, GetLastError());
325 WCMD_output_asis_len(lpMsgBuf
, lstrlenW(lpMsgBuf
),
326 GetStdHandle(STD_ERROR_HANDLE
));
327 LocalFree (lpMsgBuf
);
328 WCMD_output_asis_len (newline
, lstrlenW(newline
),
329 GetStdHandle(STD_ERROR_HANDLE
));
333 /******************************************************************************
336 * Display the prompt on STDout
340 static void WCMD_show_prompt (void) {
343 WCHAR out_string
[MAX_PATH
], curdir
[MAX_PATH
], prompt_string
[MAX_PATH
];
346 static const WCHAR envPrompt
[] = {'P','R','O','M','P','T','\0'};
348 len
= GetEnvironmentVariableW(envPrompt
, prompt_string
,
349 sizeof(prompt_string
)/sizeof(WCHAR
));
350 if ((len
== 0) || (len
>= (sizeof(prompt_string
)/sizeof(WCHAR
)))) {
351 static const WCHAR dfltPrompt
[] = {'$','P','$','G','\0'};
352 strcpyW (prompt_string
, dfltPrompt
);
366 switch (toupper(*p
)) {
380 GetDateFormatW(LOCALE_USER_DEFAULT
, DATE_SHORTDATE
, NULL
, NULL
, q
, MAX_PATH
);
399 status
= GetCurrentDirectoryW(sizeof(curdir
)/sizeof(WCHAR
), curdir
);
405 status
= GetCurrentDirectoryW(sizeof(curdir
)/sizeof(WCHAR
), curdir
);
418 GetTimeFormatW(LOCALE_USER_DEFAULT
, 0, NULL
, NULL
, q
, MAX_PATH
);
422 strcatW (q
, version_string
);
429 if (pushd_directories
) {
430 memset(q
, '+', pushd_directories
->u
.stackdepth
);
431 q
= q
+ pushd_directories
->u
.stackdepth
;
439 WCMD_output_asis (out_string
);
443 /*************************************************************************
445 * A wide version of strdup as its missing from unicode.h
447 WCHAR
*WCMD_strdupW(const WCHAR
*input
) {
448 int len
=strlenW(input
)+1;
449 WCHAR
*result
= HeapAlloc(GetProcessHeap(), 0, len
* sizeof(WCHAR
));
450 memcpy(result
, input
, len
* sizeof(WCHAR
));
454 /*************************************************************************
456 * Replaces a portion of a Unicode string with the specified string.
457 * It's up to the caller to ensure there is enough space in the
458 * destination buffer.
460 void WCMD_strsubstW(WCHAR
*start
, const WCHAR
*next
, const WCHAR
*insert
, int len
) {
463 len
=insert
? lstrlenW(insert
) : 0;
464 if (start
+len
!= next
)
465 memmove(start
+len
, next
, (strlenW(next
) + 1) * sizeof(*next
));
467 memcpy(start
, insert
, len
* sizeof(*insert
));
470 /***************************************************************************
471 * WCMD_skip_leading_spaces
473 * Return a pointer to the first non-whitespace character of string.
474 * Does not modify the input string.
476 WCHAR
*WCMD_skip_leading_spaces (WCHAR
*string
) {
481 while (*ptr
== ' ' || *ptr
== '\t') ptr
++;
485 /***************************************************************************
486 * WCMD_keyword_ws_found
488 * Checks if the string located at ptr matches a keyword (of length len)
489 * followed by a whitespace character (space or tab)
491 BOOL
WCMD_keyword_ws_found(const WCHAR
*keyword
, int len
, const WCHAR
*ptr
) {
492 return (CompareStringW(LOCALE_USER_DEFAULT
, NORM_IGNORECASE
| SORT_STRINGSORT
,
493 ptr
, len
, keyword
, len
) == CSTR_EQUAL
)
494 && ((*(ptr
+ len
) == ' ') || (*(ptr
+ len
) == '\t'));
497 /*************************************************************************
498 * WCMD_opt_s_strip_quotes
500 * Remove first and last quote WCHARacters, preserving all other text
502 void WCMD_opt_s_strip_quotes(WCHAR
*cmd
) {
503 WCHAR
*src
= cmd
+ 1, *dest
= cmd
, *lastq
= NULL
;
504 while((*dest
=*src
) != '\0') {
511 while ((*dest
++=*lastq
++) != 0)
517 /*************************************************************************
518 * WCMD_is_magic_envvar
519 * Return TRUE if s is '%'magicvar'%'
520 * and is not masked by a real environment variable.
523 static inline BOOL
WCMD_is_magic_envvar(const WCHAR
*s
, const WCHAR
*magicvar
)
528 return FALSE
; /* Didn't begin with % */
530 if (len
< 2 || s
[len
-1] != '%')
531 return FALSE
; /* Didn't end with another % */
533 if (CompareStringW(LOCALE_USER_DEFAULT
,
534 NORM_IGNORECASE
| SORT_STRINGSORT
,
535 s
+1, len
-2, magicvar
, -1) != CSTR_EQUAL
) {
536 /* Name doesn't match. */
540 if (GetEnvironmentVariableW(magicvar
, NULL
, 0) > 0) {
541 /* Masked by real environment variable. */
548 /*************************************************************************
551 * Expands environment variables, allowing for WCHARacter substitution
553 static WCHAR
*WCMD_expand_envvar(WCHAR
*start
,
554 const WCHAR
*forVar
, const WCHAR
*forVal
) {
555 WCHAR
*endOfVar
= NULL
, *s
;
556 WCHAR
*colonpos
= NULL
;
557 WCHAR thisVar
[MAXSTRING
];
558 WCHAR thisVarContents
[MAXSTRING
];
559 WCHAR savedchar
= 0x00;
562 static const WCHAR ErrorLvl
[] = {'E','R','R','O','R','L','E','V','E','L','\0'};
563 static const WCHAR Date
[] = {'D','A','T','E','\0'};
564 static const WCHAR Time
[] = {'T','I','M','E','\0'};
565 static const WCHAR Cd
[] = {'C','D','\0'};
566 static const WCHAR Random
[] = {'R','A','N','D','O','M','\0'};
567 static const WCHAR Delims
[] = {'%',' ',':','\0'};
569 WINE_TRACE("Expanding: %s (%s,%s)\n", wine_dbgstr_w(start
),
570 wine_dbgstr_w(forVal
), wine_dbgstr_w(forVar
));
572 /* Find the end of the environment variable, and extract name */
573 endOfVar
= strpbrkW(start
+1, Delims
);
575 if (endOfVar
== NULL
|| *endOfVar
==' ') {
577 /* In batch program, missing terminator for % and no following
578 ':' just removes the '%' */
580 WCMD_strsubstW(start
, start
+ 1, NULL
, 0);
584 /* In command processing, just ignore it - allows command line
585 syntax like: for %i in (a.a) do echo %i */
590 /* If ':' found, process remaining up until '%' (or stop at ':' if
592 if (*endOfVar
==':') {
593 WCHAR
*endOfVar2
= strchrW(endOfVar
+1, '%');
594 if (endOfVar2
!= NULL
) endOfVar
= endOfVar2
;
597 memcpy(thisVar
, start
, ((endOfVar
- start
) + 1) * sizeof(WCHAR
));
598 thisVar
[(endOfVar
- start
)+1] = 0x00;
599 colonpos
= strchrW(thisVar
+1, ':');
601 /* If there's complex substitution, just need %var% for now
602 to get the expanded data to play with */
605 savedchar
= *(colonpos
+1);
606 *(colonpos
+1) = 0x00;
609 WINE_TRACE("Retrieving contents of %s\n", wine_dbgstr_w(thisVar
));
611 /* Expand to contents, if unchanged, return */
612 /* Handle DATE, TIME, ERRORLEVEL and CD replacements allowing */
613 /* override if existing env var called that name */
614 if (WCMD_is_magic_envvar(thisVar
, ErrorLvl
)) {
615 static const WCHAR fmt
[] = {'%','d','\0'};
616 wsprintfW(thisVarContents
, fmt
, errorlevel
);
617 len
= strlenW(thisVarContents
);
618 } else if (WCMD_is_magic_envvar(thisVar
, Date
)) {
619 GetDateFormatW(LOCALE_USER_DEFAULT
, DATE_SHORTDATE
, NULL
,
620 NULL
, thisVarContents
, MAXSTRING
);
621 len
= strlenW(thisVarContents
);
622 } else if (WCMD_is_magic_envvar(thisVar
, Time
)) {
623 GetTimeFormatW(LOCALE_USER_DEFAULT
, TIME_NOSECONDS
, NULL
,
624 NULL
, thisVarContents
, MAXSTRING
);
625 len
= strlenW(thisVarContents
);
626 } else if (WCMD_is_magic_envvar(thisVar
, Cd
)) {
627 GetCurrentDirectoryW(MAXSTRING
, thisVarContents
);
628 len
= strlenW(thisVarContents
);
629 } else if (WCMD_is_magic_envvar(thisVar
, Random
)) {
630 static const WCHAR fmt
[] = {'%','d','\0'};
631 wsprintfW(thisVarContents
, fmt
, rand() % 32768);
632 len
= strlenW(thisVarContents
);
634 /* Look for a matching 'for' variable */
636 (CompareStringW(LOCALE_USER_DEFAULT
,
639 (colonpos
- thisVar
) - 1,
640 forVar
, -1) == CSTR_EQUAL
)) {
641 strcpyW(thisVarContents
, forVal
);
642 len
= strlenW(thisVarContents
);
646 len
= ExpandEnvironmentStringsW(thisVar
, thisVarContents
,
647 sizeof(thisVarContents
)/sizeof(WCHAR
));
653 /* In a batch program, unknown env vars are replaced with nothing,
654 note syntax %garbage:1,3% results in anything after the ':'
656 From the command line, you just get back what you entered */
657 if (lstrcmpiW(thisVar
, thisVarContents
) == 0) {
659 /* Restore the complex part after the compare */
662 *(colonpos
+1) = savedchar
;
665 /* Command line - just ignore this */
666 if (context
== NULL
) return endOfVar
+1;
669 /* Batch - replace unknown env var with nothing */
670 if (colonpos
== NULL
) {
671 WCMD_strsubstW(start
, endOfVar
+ 1, NULL
, 0);
673 len
= strlenW(thisVar
);
674 thisVar
[len
-1] = 0x00;
675 /* If %:...% supplied, : is retained */
676 if (colonpos
== thisVar
+1) {
677 WCMD_strsubstW(start
, endOfVar
+ 1, colonpos
, -1);
679 WCMD_strsubstW(start
, endOfVar
+ 1, colonpos
+ 1, -1);
686 /* See if we need to do complex substitution (any ':'s), if not
687 then our work here is done */
688 if (colonpos
== NULL
) {
689 WCMD_strsubstW(start
, endOfVar
+ 1, thisVarContents
, -1);
693 /* Restore complex bit */
695 *(colonpos
+1) = savedchar
;
698 Handle complex substitutions:
699 xxx=yyy (replace xxx with yyy)
700 *xxx=yyy (replace up to and including xxx with yyy)
701 ~x (from x WCHARs in)
702 ~-x (from x WCHARs from the end)
703 ~x,y (from x WCHARs in for y WCHARacters)
704 ~x,-y (from x WCHARs in until y WCHARacters from the end)
707 /* ~ is substring manipulation */
708 if (savedchar
== '~') {
710 int substrposition
, substrlength
= 0;
711 WCHAR
*commapos
= strchrW(colonpos
+2, ',');
714 substrposition
= atolW(colonpos
+2);
715 if (commapos
) substrlength
= atolW(commapos
+1);
718 if (substrposition
>= 0) {
719 startCopy
= &thisVarContents
[min(substrposition
, len
)];
721 startCopy
= &thisVarContents
[max(0, len
+substrposition
-1)];
724 if (commapos
== NULL
) {
726 WCMD_strsubstW(start
, endOfVar
+ 1, startCopy
, -1);
727 } else if (substrlength
< 0) {
729 int copybytes
= (len
+substrlength
-1)-(startCopy
-thisVarContents
);
730 if (copybytes
> len
) copybytes
= len
;
731 else if (copybytes
< 0) copybytes
= 0;
732 WCMD_strsubstW(start
, endOfVar
+ 1, startCopy
, copybytes
);
734 WCMD_strsubstW(start
, endOfVar
+ 1, startCopy
, substrlength
);
739 /* search and replace manipulation */
741 WCHAR
*equalspos
= strstrW(colonpos
, equalsW
);
742 WCHAR
*replacewith
= equalspos
+1;
747 if (equalspos
== NULL
) return start
+1;
748 s
= WCMD_strdupW(endOfVar
+ 1);
750 /* Null terminate both strings */
751 thisVar
[strlenW(thisVar
)-1] = 0x00;
754 /* Since we need to be case insensitive, copy the 2 buffers */
755 searchIn
= WCMD_strdupW(thisVarContents
);
756 CharUpperBuffW(searchIn
, strlenW(thisVarContents
));
757 searchFor
= WCMD_strdupW(colonpos
+1);
758 CharUpperBuffW(searchFor
, strlenW(colonpos
+1));
760 /* Handle wildcard case */
761 if (*(colonpos
+1) == '*') {
762 /* Search for string to replace */
763 found
= strstrW(searchIn
, searchFor
+1);
767 strcpyW(start
, replacewith
);
768 strcatW(start
, thisVarContents
+ (found
-searchIn
) + strlenW(searchFor
+1));
772 strcpyW(start
, thisVarContents
);
777 /* Loop replacing all instances */
778 WCHAR
*lastFound
= searchIn
;
779 WCHAR
*outputposn
= start
;
782 while ((found
= strstrW(lastFound
, searchFor
))) {
783 lstrcpynW(outputposn
,
784 thisVarContents
+ (lastFound
-searchIn
),
785 (found
- lastFound
)+1);
786 outputposn
= outputposn
+ (found
- lastFound
);
787 strcatW(outputposn
, replacewith
);
788 outputposn
= outputposn
+ strlenW(replacewith
);
789 lastFound
= found
+ strlenW(searchFor
);
792 thisVarContents
+ (lastFound
-searchIn
));
793 strcatW(outputposn
, s
);
795 HeapFree(GetProcessHeap(), 0, s
);
796 HeapFree(GetProcessHeap(), 0, searchIn
);
797 HeapFree(GetProcessHeap(), 0, searchFor
);
803 /*****************************************************************************
804 * Expand the command. Native expands lines from batch programs as they are
805 * read in and not again, except for 'for' variable substitution.
806 * eg. As evidence, "echo %1 && shift && echo %1" or "echo %%path%%"
808 static void handleExpansion(WCHAR
*cmd
, BOOL justFors
,
809 const WCHAR
*forVariable
, const WCHAR
*forValue
) {
811 /* For commands in a context (batch program): */
812 /* Expand environment variables in a batch file %{0-9} first */
813 /* including support for any ~ modifiers */
815 /* Expand the DATE, TIME, CD, RANDOM and ERRORLEVEL special */
816 /* names allowing environment variable overrides */
817 /* NOTE: To support the %PATH:xxx% syntax, also perform */
818 /* manual expansion of environment variables here */
824 while ((p
= strchrW(p
, '%'))) {
826 WINE_TRACE("Translate command:%s %d (at: %s)\n",
827 wine_dbgstr_w(cmd
), justFors
, wine_dbgstr_w(p
));
830 /* Don't touch %% unless its in Batch */
831 if (!justFors
&& *(p
+1) == '%') {
833 WCMD_strsubstW(p
, p
+1, NULL
, 0);
837 /* Replace %~ modifications if in batch program */
838 } else if (*(p
+1) == '~') {
839 WCMD_HandleTildaModifiers(&p
, forVariable
, forValue
, justFors
);
842 /* Replace use of %0...%9 if in batch program*/
843 } else if (!justFors
&& context
&& (i
>= 0) && (i
<= 9)) {
844 t
= WCMD_parameter(context
-> command
, i
+ context
-> shift_count
[i
], NULL
, NULL
);
845 WCMD_strsubstW(p
, p
+2, t
, -1);
847 /* Replace use of %* if in batch program*/
848 } else if (!justFors
&& context
&& *(p
+1)=='*') {
849 WCHAR
*startOfParms
= NULL
;
850 t
= WCMD_parameter(context
-> command
, 1, &startOfParms
, NULL
);
851 if (startOfParms
!= NULL
)
852 WCMD_strsubstW(p
, p
+2, startOfParms
, -1);
854 WCMD_strsubstW(p
, p
+2, NULL
, 0);
856 } else if (forVariable
&&
857 (CompareStringW(LOCALE_USER_DEFAULT
,
860 strlenW(forVariable
),
861 forVariable
, -1) == CSTR_EQUAL
)) {
862 WCMD_strsubstW(p
, p
+ strlenW(forVariable
), forValue
, -1);
864 } else if (!justFors
) {
865 p
= WCMD_expand_envvar(p
, forVariable
, forValue
);
867 /* In a FOR loop, see if this is the variable to replace */
868 } else { /* Ignore %'s on second pass of batch program */
877 /*******************************************************************
878 * WCMD_parse - parse a command into parameters and qualifiers.
880 * On exit, all qualifiers are concatenated into q, the first string
881 * not beginning with "/" is in p1 and the
882 * second in p2. Any subsequent non-qualifier strings are lost.
883 * Parameters in quotes are handled.
885 static void WCMD_parse (const WCHAR
*s
, WCHAR
*q
, WCHAR
*p1
, WCHAR
*p2
)
889 *q
= *p1
= *p2
= '\0';
894 while ((*s
!= '\0') && (*s
!= ' ') && *s
!= '/') {
895 *q
++ = toupperW (*s
++);
905 while ((*s
!= '\0') && (*s
!= '"')) {
906 if (p
== 0) *p1
++ = *s
++;
907 else if (p
== 1) *p2
++ = *s
++;
910 if (p
== 0) *p1
= '\0';
911 if (p
== 1) *p2
= '\0';
918 while ((*s
!= '\0') && (*s
!= ' ') && (*s
!= '\t')
919 && (*s
!= '=') && (*s
!= ',') ) {
920 if (p
== 0) *p1
++ = *s
++;
921 else if (p
== 1) *p2
++ = *s
++;
924 /* Skip concurrent parms */
925 while ((*s
== ' ') || (*s
== '\t') || (*s
== '=') || (*s
== ',') ) s
++;
927 if (p
== 0) *p1
= '\0';
928 if (p
== 1) *p2
= '\0';
934 static void init_msvcrt_io_block(STARTUPINFOW
* st
)
937 /* fetch the parent MSVCRT info block if any, so that the child can use the
938 * same handles as its grand-father
940 st_p
.cb
= sizeof(STARTUPINFOW
);
941 GetStartupInfoW(&st_p
);
942 st
->cbReserved2
= st_p
.cbReserved2
;
943 st
->lpReserved2
= st_p
.lpReserved2
;
944 if (st_p
.cbReserved2
&& st_p
.lpReserved2
)
946 /* Override the entries for fd 0,1,2 if we happened
947 * to change those std handles (this depends on the way cmd sets
948 * its new input & output handles)
950 size_t sz
= max(sizeof(unsigned) + (sizeof(char) + sizeof(HANDLE
)) * 3, st_p
.cbReserved2
);
951 BYTE
* ptr
= HeapAlloc(GetProcessHeap(), 0, sz
);
954 unsigned num
= *(unsigned*)st_p
.lpReserved2
;
955 char* flags
= (char*)(ptr
+ sizeof(unsigned));
956 HANDLE
* handles
= (HANDLE
*)(flags
+ num
* sizeof(char));
958 memcpy(ptr
, st_p
.lpReserved2
, st_p
.cbReserved2
);
959 st
->cbReserved2
= sz
;
960 st
->lpReserved2
= ptr
;
962 #define WX_OPEN 0x01 /* see dlls/msvcrt/file.c */
963 if (num
<= 0 || (flags
[0] & WX_OPEN
))
965 handles
[0] = GetStdHandle(STD_INPUT_HANDLE
);
968 if (num
<= 1 || (flags
[1] & WX_OPEN
))
970 handles
[1] = GetStdHandle(STD_OUTPUT_HANDLE
);
973 if (num
<= 2 || (flags
[2] & WX_OPEN
))
975 handles
[2] = GetStdHandle(STD_ERROR_HANDLE
);
983 /******************************************************************************
986 * Execute a command line as an external program. Must allow recursion.
989 * Manual testing under windows shows PATHEXT plays a key part in this,
990 * and the search algorithm and precedence appears to be as follows.
993 * If directory supplied on command, just use that directory
994 * If extension supplied on command, look for that explicit name first
995 * Otherwise, search in each directory on the path
997 * If extension supplied on command, look for that explicit name first
998 * Then look for supplied name .* (even if extension supplied, so
999 * 'garbage.exe' will match 'garbage.exe.cmd')
1000 * If any found, cycle through PATHEXT looking for name.exe one by one
1002 * Once a match has been found, it is launched - Code currently uses
1003 * findexecutable to achieve this which is left untouched.
1006 void WCMD_run_program (WCHAR
*command
, int called
) {
1008 WCHAR temp
[MAX_PATH
];
1009 WCHAR pathtosearch
[MAXSTRING
];
1011 WCHAR stemofsearch
[MAX_PATH
]; /* maximum allowed executable name is
1012 MAX_PATH, including null character */
1014 WCHAR pathext
[MAXSTRING
];
1015 BOOL extensionsupplied
= FALSE
;
1016 BOOL launched
= FALSE
;
1018 BOOL assumeInternal
= FALSE
;
1020 static const WCHAR envPath
[] = {'P','A','T','H','\0'};
1021 static const WCHAR envPathExt
[] = {'P','A','T','H','E','X','T','\0'};
1022 static const WCHAR delims
[] = {'/','\\',':','\0'};
1024 WCMD_parse (command
, quals
, param1
, param2
); /* Quick way to get the filename */
1025 if (!(*param1
) && !(*param2
))
1028 /* Calculate the search path and stem to search for */
1029 if (strpbrkW (param1
, delims
) == NULL
) { /* No explicit path given, search path */
1030 static const WCHAR curDir
[] = {'.',';','\0'};
1031 strcpyW(pathtosearch
, curDir
);
1032 len
= GetEnvironmentVariableW(envPath
, &pathtosearch
[2], (sizeof(pathtosearch
)/sizeof(WCHAR
))-2);
1033 if ((len
== 0) || (len
>= (sizeof(pathtosearch
)/sizeof(WCHAR
)) - 2)) {
1034 static const WCHAR curDir
[] = {'.','\0'};
1035 strcpyW (pathtosearch
, curDir
);
1037 if (strchrW(param1
, '.') != NULL
) extensionsupplied
= TRUE
;
1038 if (strlenW(param1
) >= MAX_PATH
)
1040 WCMD_output_asis(WCMD_LoadMessage(WCMD_LINETOOLONG
));
1044 strcpyW(stemofsearch
, param1
);
1048 /* Convert eg. ..\fred to include a directory by removing file part */
1049 GetFullPathNameW(param1
, sizeof(pathtosearch
)/sizeof(WCHAR
), pathtosearch
, NULL
);
1050 lastSlash
= strrchrW(pathtosearch
, '\\');
1051 if (lastSlash
&& strchrW(lastSlash
, '.') != NULL
) extensionsupplied
= TRUE
;
1052 strcpyW(stemofsearch
, lastSlash
+1);
1054 /* Reduce pathtosearch to a path with trailing '\' to support c:\a.bat and
1055 c:\windows\a.bat syntax */
1056 if (lastSlash
) *(lastSlash
+ 1) = 0x00;
1059 /* Now extract PATHEXT */
1060 len
= GetEnvironmentVariableW(envPathExt
, pathext
, sizeof(pathext
)/sizeof(WCHAR
));
1061 if ((len
== 0) || (len
>= (sizeof(pathext
)/sizeof(WCHAR
)))) {
1062 static const WCHAR dfltPathExt
[] = {'.','b','a','t',';',
1063 '.','c','o','m',';',
1064 '.','c','m','d',';',
1065 '.','e','x','e','\0'};
1066 strcpyW (pathext
, dfltPathExt
);
1069 /* Loop through the search path, dir by dir */
1070 pathposn
= pathtosearch
;
1071 WINE_TRACE("Searching in '%s' for '%s'\n", wine_dbgstr_w(pathtosearch
),
1072 wine_dbgstr_w(stemofsearch
));
1073 while (!launched
&& pathposn
) {
1075 WCHAR thisDir
[MAX_PATH
] = {'\0'};
1078 static const WCHAR slashW
[] = {'\\','\0'};
1080 /* Work on the first directory on the search path */
1081 pos
= strchrW(pathposn
, ';');
1083 memcpy(thisDir
, pathposn
, (pos
-pathposn
) * sizeof(WCHAR
));
1084 thisDir
[(pos
-pathposn
)] = 0x00;
1088 strcpyW(thisDir
, pathposn
);
1092 /* Since you can have eg. ..\.. on the path, need to expand
1093 to full information */
1094 strcpyW(temp
, thisDir
);
1095 GetFullPathNameW(temp
, MAX_PATH
, thisDir
, NULL
);
1097 /* 1. If extension supplied, see if that file exists */
1098 strcatW(thisDir
, slashW
);
1099 strcatW(thisDir
, stemofsearch
);
1100 pos
= &thisDir
[strlenW(thisDir
)]; /* Pos = end of name */
1102 /* 1. If extension supplied, see if that file exists */
1103 if (extensionsupplied
) {
1104 if (GetFileAttributesW(thisDir
) != INVALID_FILE_ATTRIBUTES
) {
1109 /* 2. Any .* matches? */
1112 WIN32_FIND_DATAW finddata
;
1113 static const WCHAR allFiles
[] = {'.','*','\0'};
1115 strcatW(thisDir
,allFiles
);
1116 h
= FindFirstFileW(thisDir
, &finddata
);
1118 if (h
!= INVALID_HANDLE_VALUE
) {
1120 WCHAR
*thisExt
= pathext
;
1122 /* 3. Yes - Try each path ext */
1124 WCHAR
*nextExt
= strchrW(thisExt
, ';');
1127 memcpy(pos
, thisExt
, (nextExt
-thisExt
) * sizeof(WCHAR
));
1128 pos
[(nextExt
-thisExt
)] = 0x00;
1129 thisExt
= nextExt
+1;
1131 strcpyW(pos
, thisExt
);
1135 if (GetFileAttributesW(thisDir
) != INVALID_FILE_ATTRIBUTES
) {
1143 /* Internal programs won't be picked up by this search, so even
1144 though not found, try one last createprocess and wait for it
1146 Note: Ideally we could tell between a console app (wait) and a
1147 windows app, but the API's for it fail in this case */
1148 if (!found
&& pathposn
== NULL
) {
1149 WINE_TRACE("ASSUMING INTERNAL\n");
1150 assumeInternal
= TRUE
;
1152 WINE_TRACE("Found as %s\n", wine_dbgstr_w(thisDir
));
1155 /* Once found, launch it */
1156 if (found
|| assumeInternal
) {
1158 PROCESS_INFORMATION pe
;
1162 WCHAR
*ext
= strrchrW( thisDir
, '.' );
1163 static const WCHAR batExt
[] = {'.','b','a','t','\0'};
1164 static const WCHAR cmdExt
[] = {'.','c','m','d','\0'};
1168 /* Special case BAT and CMD */
1169 if (ext
&& !strcmpiW(ext
, batExt
)) {
1170 WCMD_batch (thisDir
, command
, called
, NULL
, INVALID_HANDLE_VALUE
);
1172 } else if (ext
&& !strcmpiW(ext
, cmdExt
)) {
1173 WCMD_batch (thisDir
, command
, called
, NULL
, INVALID_HANDLE_VALUE
);
1177 /* thisDir contains the file to be launched, but with what?
1178 eg. a.exe will require a.exe to be launched, a.html may be iexplore */
1179 hinst
= FindExecutableW (thisDir
, NULL
, temp
);
1180 if ((INT_PTR
)hinst
< 32)
1183 console
= SHGetFileInfoW(temp
, 0, &psfi
, sizeof(psfi
), SHGFI_EXETYPE
);
1185 ZeroMemory (&st
, sizeof(STARTUPINFOW
));
1186 st
.cb
= sizeof(STARTUPINFOW
);
1187 init_msvcrt_io_block(&st
);
1189 /* Launch the process and if a CUI wait on it to complete
1190 Note: Launching internal wine processes cannot specify a full path to exe */
1191 status
= CreateProcessW(assumeInternal
?NULL
: thisDir
,
1192 command
, NULL
, NULL
, TRUE
, 0, NULL
, NULL
, &st
, &pe
);
1193 if ((opt_c
|| opt_k
) && !opt_s
&& !status
1194 && GetLastError()==ERROR_FILE_NOT_FOUND
&& command
[0]=='\"') {
1195 /* strip first and last quote WCHARacters and try again */
1196 WCMD_opt_s_strip_quotes(command
);
1198 WCMD_run_program(command
, called
);
1205 if (!assumeInternal
&& !console
) errorlevel
= 0;
1208 /* Always wait when called in a batch program context */
1209 if (assumeInternal
|| context
|| !HIWORD(console
)) WaitForSingleObject (pe
.hProcess
, INFINITE
);
1210 GetExitCodeProcess (pe
.hProcess
, &errorlevel
);
1211 if (errorlevel
== STILL_ACTIVE
) errorlevel
= 0;
1213 CloseHandle(pe
.hProcess
);
1214 CloseHandle(pe
.hThread
);
1220 /* Not found anywhere - give up */
1221 SetLastError(ERROR_FILE_NOT_FOUND
);
1222 WCMD_print_error ();
1224 /* If a command fails to launch, it sets errorlevel 9009 - which
1225 does not seem to have any associated constant definition */
1231 /*****************************************************************************
1232 * Process one command. If the command is EXIT this routine does not return.
1233 * We will recurse through here executing batch files.
1235 void WCMD_execute (const WCHAR
*command
, const WCHAR
*redirects
,
1236 const WCHAR
*forVariable
, const WCHAR
*forValue
,
1239 WCHAR
*cmd
, *p
, *redir
;
1241 DWORD count
, creationDisposition
;
1244 SECURITY_ATTRIBUTES sa
;
1245 WCHAR
*new_cmd
= NULL
;
1246 WCHAR
*new_redir
= NULL
;
1247 HANDLE old_stdhandles
[3] = {GetStdHandle (STD_INPUT_HANDLE
),
1248 GetStdHandle (STD_OUTPUT_HANDLE
),
1249 GetStdHandle (STD_ERROR_HANDLE
)};
1250 DWORD idx_stdhandles
[3] = {STD_INPUT_HANDLE
,
1253 BOOL prev_echo_mode
, piped
= FALSE
;
1255 WINE_TRACE("command on entry:%s (%p), with forVariable '%s'='%s'\n",
1256 wine_dbgstr_w(command
), cmdList
,
1257 wine_dbgstr_w(forVariable
), wine_dbgstr_w(forValue
));
1259 /* If the next command is a pipe then we implement pipes by redirecting
1260 the output from this command to a temp file and input into the
1261 next command from that temp file.
1262 FIXME: Use of named pipes would make more sense here as currently this
1263 process has to finish before the next one can start but this requires
1264 a change to not wait for the first app to finish but rather the pipe */
1265 if (cmdList
&& (*cmdList
)->nextcommand
&&
1266 (*cmdList
)->nextcommand
->prevDelim
== CMD_PIPE
) {
1268 WCHAR temp_path
[MAX_PATH
];
1269 static const WCHAR cmdW
[] = {'C','M','D','\0'};
1271 /* Remember piping is in action */
1272 WINE_TRACE("Output needs to be piped\n");
1275 /* Generate a unique temporary filename */
1276 GetTempPathW(sizeof(temp_path
)/sizeof(WCHAR
), temp_path
);
1277 GetTempFileNameW(temp_path
, cmdW
, 0, (*cmdList
)->nextcommand
->pipeFile
);
1278 WINE_TRACE("Using temporary file of %s\n",
1279 wine_dbgstr_w((*cmdList
)->nextcommand
->pipeFile
));
1282 /* Move copy of the command onto the heap so it can be expanded */
1283 new_cmd
= HeapAlloc( GetProcessHeap(), 0, MAXSTRING
* sizeof(WCHAR
));
1286 WINE_ERR("Could not allocate memory for new_cmd\n");
1289 strcpyW(new_cmd
, command
);
1291 /* Move copy of the redirects onto the heap so it can be expanded */
1292 new_redir
= HeapAlloc( GetProcessHeap(), 0, MAXSTRING
* sizeof(WCHAR
));
1295 WINE_ERR("Could not allocate memory for new_redir\n");
1296 HeapFree( GetProcessHeap(), 0, new_cmd
);
1300 /* If piped output, send stdout to the pipe by appending >filename to redirects */
1302 static const WCHAR redirOut
[] = {'%','s',' ','>',' ','%','s','\0'};
1303 wsprintfW (new_redir
, redirOut
, redirects
, (*cmdList
)->nextcommand
->pipeFile
);
1304 WINE_TRACE("Redirects now %s\n", wine_dbgstr_w(new_redir
));
1306 strcpyW(new_redir
, redirects
);
1309 /* Expand variables in command line mode only (batch mode will
1310 be expanded as the line is read in, except for 'for' loops) */
1311 handleExpansion(new_cmd
, (context
!= NULL
), forVariable
, forValue
);
1312 handleExpansion(new_redir
, (context
!= NULL
), forVariable
, forValue
);
1316 * Changing default drive has to be handled as a special case.
1319 if ((cmd
[1] == ':') && IsCharAlphaW(cmd
[0]) && (strlenW(cmd
) == 2)) {
1321 WCHAR dir
[MAX_PATH
];
1323 /* According to MSDN CreateProcess docs, special env vars record
1324 the current directory on each drive, in the form =C:
1325 so see if one specified, and if so go back to it */
1326 strcpyW(envvar
, equalsW
);
1327 strcatW(envvar
, cmd
);
1328 if (GetEnvironmentVariableW(envvar
, dir
, MAX_PATH
) == 0) {
1329 static const WCHAR fmt
[] = {'%','s','\\','\0'};
1330 wsprintfW(cmd
, fmt
, cmd
);
1331 WINE_TRACE("No special directory settings, using dir of %s\n", wine_dbgstr_w(cmd
));
1333 WINE_TRACE("Got directory %s as %s\n", wine_dbgstr_w(envvar
), wine_dbgstr_w(cmd
));
1334 status
= SetCurrentDirectoryW(cmd
);
1335 if (!status
) WCMD_print_error ();
1336 HeapFree( GetProcessHeap(), 0, cmd
);
1337 HeapFree( GetProcessHeap(), 0, new_redir
);
1341 sa
.nLength
= sizeof(sa
);
1342 sa
.lpSecurityDescriptor
= NULL
;
1343 sa
.bInheritHandle
= TRUE
;
1346 * Redirect stdin, stdout and/or stderr if required.
1349 /* STDIN could come from a preceding pipe, so delete on close if it does */
1350 if (cmdList
&& (*cmdList
)->pipeFile
[0] != 0x00) {
1351 WINE_TRACE("Input coming from %s\n", wine_dbgstr_w((*cmdList
)->pipeFile
));
1352 h
= CreateFileW((*cmdList
)->pipeFile
, GENERIC_READ
,
1353 FILE_SHARE_READ
, &sa
, OPEN_EXISTING
,
1354 FILE_ATTRIBUTE_NORMAL
| FILE_FLAG_DELETE_ON_CLOSE
, NULL
);
1355 if (h
== INVALID_HANDLE_VALUE
) {
1356 WCMD_print_error ();
1357 HeapFree( GetProcessHeap(), 0, cmd
);
1358 HeapFree( GetProcessHeap(), 0, new_redir
);
1361 SetStdHandle (STD_INPUT_HANDLE
, h
);
1363 /* No need to remember the temporary name any longer once opened */
1364 (*cmdList
)->pipeFile
[0] = 0x00;
1366 /* Otherwise STDIN could come from a '<' redirect */
1367 } else if ((p
= strchrW(new_redir
,'<')) != NULL
) {
1368 h
= CreateFileW(WCMD_parameter(++p
, 0, NULL
, NULL
), GENERIC_READ
, FILE_SHARE_READ
,
1369 &sa
, OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, NULL
);
1370 if (h
== INVALID_HANDLE_VALUE
) {
1371 WCMD_print_error ();
1372 HeapFree( GetProcessHeap(), 0, cmd
);
1373 HeapFree( GetProcessHeap(), 0, new_redir
);
1376 SetStdHandle (STD_INPUT_HANDLE
, h
);
1379 /* Scan the whole command looking for > and 2> */
1381 while (redir
!= NULL
&& ((p
= strchrW(redir
,'>')) != NULL
)) {
1384 if (p
> redir
&& (*(p
-1)=='2'))
1391 creationDisposition
= OPEN_ALWAYS
;
1395 creationDisposition
= CREATE_ALWAYS
;
1398 /* Add support for 2>&1 */
1401 int idx
= *(p
+1) - '0';
1403 if (DuplicateHandle(GetCurrentProcess(),
1404 GetStdHandle(idx_stdhandles
[idx
]),
1405 GetCurrentProcess(),
1407 0, TRUE
, DUPLICATE_SAME_ACCESS
) == 0) {
1408 WINE_FIXME("Duplicating handle failed with gle %d\n", GetLastError());
1410 WINE_TRACE("Redirect %d (%p) to %d (%p)\n", handle
, GetStdHandle(idx_stdhandles
[idx
]), idx
, h
);
1413 WCHAR
*param
= WCMD_parameter(p
, 0, NULL
, NULL
);
1414 h
= CreateFileW(param
, GENERIC_WRITE
, 0, &sa
, creationDisposition
,
1415 FILE_ATTRIBUTE_NORMAL
, NULL
);
1416 if (h
== INVALID_HANDLE_VALUE
) {
1417 WCMD_print_error ();
1418 HeapFree( GetProcessHeap(), 0, cmd
);
1419 HeapFree( GetProcessHeap(), 0, new_redir
);
1422 if (SetFilePointer (h
, 0, NULL
, FILE_END
) ==
1423 INVALID_SET_FILE_POINTER
) {
1424 WCMD_print_error ();
1426 WINE_TRACE("Redirect %d to '%s' (%p)\n", handle
, wine_dbgstr_w(param
), h
);
1429 SetStdHandle (idx_stdhandles
[handle
], h
);
1433 * Strip leading whitespaces, and a '@' if supplied
1435 whichcmd
= WCMD_skip_leading_spaces(cmd
);
1436 WINE_TRACE("Command: '%s'\n", wine_dbgstr_w(cmd
));
1437 if (whichcmd
[0] == '@') whichcmd
++;
1440 * Check if the command entered is internal. If it is, pass the rest of the
1441 * line down to the command. If not try to run a program.
1445 while (IsCharAlphaNumericW(whichcmd
[count
])) {
1448 for (i
=0; i
<=WCMD_EXIT
; i
++) {
1449 if (CompareStringW(LOCALE_USER_DEFAULT
, NORM_IGNORECASE
| SORT_STRINGSORT
,
1450 whichcmd
, count
, inbuilt
[i
], -1) == CSTR_EQUAL
) break;
1452 p
= WCMD_skip_leading_spaces (&whichcmd
[count
]);
1453 WCMD_parse (p
, quals
, param1
, param2
);
1454 WINE_TRACE("param1: %s, param2: %s\n", wine_dbgstr_w(param1
), wine_dbgstr_w(param2
));
1456 if (i
<= WCMD_EXIT
&& (p
[0] == '/') && (p
[1] == '?')) {
1457 /* this is a help request for a builtin program */
1459 memcpy(p
, whichcmd
, count
* sizeof(WCHAR
));
1471 WCMD_setshow_default (p
);
1474 WCMD_clear_screen ();
1483 WCMD_setshow_date ();
1493 WCMD_echo(&whichcmd
[count
]);
1496 WCMD_for (p
, cmdList
);
1499 WCMD_goto (cmdList
);
1505 WCMD_if (p
, cmdList
);
1508 WCMD_volume (TRUE
, p
);
1512 WCMD_create_dir (p
);
1518 WCMD_setshow_path (p
);
1524 WCMD_setshow_prompt ();
1534 WCMD_remove_dir (p
);
1543 WCMD_setshow_env (p
);
1549 WCMD_setshow_time ();
1552 if (strlenW(&whichcmd
[count
]) > 0)
1553 WCMD_title(&whichcmd
[count
+1]);
1559 WCMD_output(newline
);
1566 WCMD_volume (FALSE
, p
);
1575 WCMD_assoc(p
, TRUE
);
1581 WCMD_assoc(p
, FALSE
);
1590 WCMD_exit (cmdList
);
1593 prev_echo_mode
= echo_mode
;
1594 WCMD_run_program (whichcmd
, 0);
1595 echo_mode
= prev_echo_mode
;
1597 HeapFree( GetProcessHeap(), 0, cmd
);
1598 HeapFree( GetProcessHeap(), 0, new_redir
);
1600 /* Restore old handles */
1601 for (i
=0; i
<3; i
++) {
1602 if (old_stdhandles
[i
] != GetStdHandle(idx_stdhandles
[i
])) {
1603 CloseHandle (GetStdHandle (idx_stdhandles
[i
]));
1604 SetStdHandle (idx_stdhandles
[i
], old_stdhandles
[i
]);
1609 /*************************************************************************
1611 * Load a string from the resource file, handling any error
1612 * Returns string retrieved from resource file
1614 WCHAR
*WCMD_LoadMessage(UINT id
) {
1615 static WCHAR msg
[2048];
1616 static const WCHAR failedMsg
[] = {'F','a','i','l','e','d','!','\0'};
1618 if (!LoadStringW(GetModuleHandleW(NULL
), id
, msg
, sizeof(msg
)/sizeof(WCHAR
))) {
1619 WINE_FIXME("LoadString failed with %d\n", GetLastError());
1620 strcpyW(msg
, failedMsg
);
1625 /***************************************************************************
1628 * Dumps out the parsed command line to ensure syntax is correct
1630 static void WCMD_DumpCommands(CMD_LIST
*commands
) {
1631 CMD_LIST
*thisCmd
= commands
;
1633 WINE_TRACE("Parsed line:\n");
1634 while (thisCmd
!= NULL
) {
1635 WINE_TRACE("%p %d %2.2d %p %s Redir:%s\n",
1638 thisCmd
->bracketDepth
,
1639 thisCmd
->nextcommand
,
1640 wine_dbgstr_w(thisCmd
->command
),
1641 wine_dbgstr_w(thisCmd
->redirects
));
1642 thisCmd
= thisCmd
->nextcommand
;
1646 /***************************************************************************
1649 * Adds a command to the current command list
1651 static void WCMD_addCommand(WCHAR
*command
, int *commandLen
,
1652 WCHAR
*redirs
, int *redirLen
,
1653 WCHAR
**copyTo
, int **copyToLen
,
1654 CMD_DELIMITERS prevDelim
, int curDepth
,
1655 CMD_LIST
**lastEntry
, CMD_LIST
**output
) {
1657 CMD_LIST
*thisEntry
= NULL
;
1659 /* Allocate storage for command */
1660 thisEntry
= HeapAlloc(GetProcessHeap(), 0, sizeof(CMD_LIST
));
1662 /* Copy in the command */
1664 thisEntry
->command
= HeapAlloc(GetProcessHeap(), 0,
1665 (*commandLen
+1) * sizeof(WCHAR
));
1666 memcpy(thisEntry
->command
, command
, *commandLen
* sizeof(WCHAR
));
1667 thisEntry
->command
[*commandLen
] = 0x00;
1669 /* Copy in the redirects */
1670 thisEntry
->redirects
= HeapAlloc(GetProcessHeap(), 0,
1671 (*redirLen
+1) * sizeof(WCHAR
));
1672 memcpy(thisEntry
->redirects
, redirs
, *redirLen
* sizeof(WCHAR
));
1673 thisEntry
->redirects
[*redirLen
] = 0x00;
1674 thisEntry
->pipeFile
[0] = 0x00;
1676 /* Reset the lengths */
1679 *copyToLen
= commandLen
;
1683 thisEntry
->command
= NULL
;
1684 thisEntry
->redirects
= NULL
;
1685 thisEntry
->pipeFile
[0] = 0x00;
1688 /* Fill in other fields */
1689 thisEntry
->nextcommand
= NULL
;
1690 thisEntry
->prevDelim
= prevDelim
;
1691 thisEntry
->bracketDepth
= curDepth
;
1693 (*lastEntry
)->nextcommand
= thisEntry
;
1695 *output
= thisEntry
;
1697 *lastEntry
= thisEntry
;
1701 /***************************************************************************
1704 * Checks if the quote pointed to is the end-quote.
1708 * 1) The current parameter ends at EOL or at the beginning
1709 * of a redirection or pipe and not in a quote section.
1711 * 2) If the next character is a space and not in a quote section.
1713 * Returns TRUE if this is an end quote, and FALSE if it is not.
1716 static BOOL
WCMD_IsEndQuote(const WCHAR
*quote
, int quoteIndex
)
1718 int quoteCount
= quoteIndex
;
1721 /* If we are not in a quoted section, then we are not an end-quote */
1727 /* Check how many quotes are left for this parameter */
1728 for(i
=0;quote
[i
];i
++)
1735 /* Quote counting ends at EOL, redirection, space or pipe if current quote is complete */
1736 else if(((quoteCount
% 2) == 0)
1737 && ((quote
[i
] == '<') || (quote
[i
] == '>') || (quote
[i
] == '|') || (quote
[i
] == ' ')))
1743 /* If the quote is part of the last part of a series of quotes-on-quotes, then it must
1745 if(quoteIndex
>= (quoteCount
/ 2))
1754 /***************************************************************************
1755 * WCMD_ReadAndParseLine
1757 * Either uses supplied input or
1758 * Reads a file from the handle, and then...
1759 * Parse the text buffer, splitting into separate commands
1760 * - unquoted && strings split 2 commands but the 2nd is flagged as
1762 * - ( as the first character just ups the bracket depth
1763 * - unquoted ) when bracket depth > 0 terminates a bracket and
1764 * adds a CMD_LIST structure with null command
1765 * - Anything else gets put into the command string (including
1768 WCHAR
*WCMD_ReadAndParseLine(const WCHAR
*optionalcmd
, CMD_LIST
**output
, HANDLE readFrom
) {
1772 WCHAR curString
[MAXSTRING
];
1773 int curStringLen
= 0;
1774 WCHAR curRedirs
[MAXSTRING
];
1775 int curRedirsLen
= 0;
1779 CMD_LIST
*lastEntry
= NULL
;
1780 CMD_DELIMITERS prevDelim
= CMD_NONE
;
1781 static WCHAR
*extraSpace
= NULL
; /* Deliberately never freed */
1782 static const WCHAR remCmd
[] = {'r','e','m'};
1783 static const WCHAR forCmd
[] = {'f','o','r'};
1784 static const WCHAR ifCmd
[] = {'i','f'};
1785 static const WCHAR ifElse
[] = {'e','l','s','e'};
1791 BOOL onlyWhiteSpace
= FALSE
;
1792 BOOL lastWasWhiteSpace
= FALSE
;
1793 BOOL lastWasDo
= FALSE
;
1794 BOOL lastWasIn
= FALSE
;
1795 BOOL lastWasElse
= FALSE
;
1796 BOOL lastWasRedirect
= TRUE
;
1798 /* Allocate working space for a command read from keyboard, file etc */
1800 extraSpace
= HeapAlloc(GetProcessHeap(), 0, (MAXSTRING
+1) * sizeof(WCHAR
));
1803 WINE_ERR("Could not allocate memory for extraSpace\n");
1807 /* If initial command read in, use that, otherwise get input from handle */
1808 if (optionalcmd
!= NULL
) {
1809 strcpyW(extraSpace
, optionalcmd
);
1810 } else if (readFrom
== INVALID_HANDLE_VALUE
) {
1811 WINE_FIXME("No command nor handle supplied\n");
1813 if (WCMD_fgets(extraSpace
, MAXSTRING
, readFrom
) == NULL
) return NULL
;
1815 curPos
= extraSpace
;
1817 /* Handle truncated input - issue warning */
1818 if (strlenW(extraSpace
) == MAXSTRING
-1) {
1819 WCMD_output_asis(WCMD_LoadMessage(WCMD_TRUNCATEDLINE
));
1820 WCMD_output_asis(extraSpace
);
1821 WCMD_output_asis(newline
);
1824 /* Replace env vars if in a batch context */
1825 if (context
) handleExpansion(extraSpace
, FALSE
, NULL
, NULL
);
1826 /* Show prompt before batch line IF echo is on and in batch program */
1827 if (context
&& echo_mode
&& extraSpace
[0] && (extraSpace
[0] != '@')) {
1828 static const WCHAR spc
[]={' ','\0'};
1829 static const WCHAR echoDot
[] = {'e','c','h','o','.'};
1830 static const WCHAR echoCol
[] = {'e','c','h','o',':'};
1831 const DWORD len
= sizeof(echoDot
)/sizeof(echoDot
[0]);
1832 DWORD curr_size
= strlenW(extraSpace
);
1833 DWORD min_len
= (curr_size
< len
? curr_size
: len
);
1835 WCMD_output_asis(extraSpace
);
1836 /* I don't know why Windows puts a space here but it does */
1837 /* Except for lines starting with 'echo.' or 'echo:'. Ask MS why */
1838 if (CompareStringW(LOCALE_SYSTEM_DEFAULT
, NORM_IGNORECASE
,
1839 extraSpace
, min_len
, echoDot
, len
) != CSTR_EQUAL
1840 && CompareStringW(LOCALE_SYSTEM_DEFAULT
, NORM_IGNORECASE
,
1841 extraSpace
, min_len
, echoCol
, len
) != CSTR_EQUAL
)
1843 WCMD_output_asis(spc
);
1845 WCMD_output_asis(newline
);
1848 /* Start with an empty string, copying to the command string */
1851 curCopyTo
= curString
;
1852 curLen
= &curStringLen
;
1853 lastWasRedirect
= FALSE
; /* Required for eg spaces between > and filename */
1855 /* Parse every character on the line being processed */
1856 while (*curPos
!= 0x00) {
1861 WINE_TRACE("Looking at '%c' (len:%d, lws:%d, ows:%d)\n", *curPos, *curLen,
1862 lastWasWhiteSpace, onlyWhiteSpace);
1865 /* Certain commands need special handling */
1866 if (curStringLen
== 0 && curCopyTo
== curString
) {
1867 static const WCHAR forDO
[] = {'d','o'};
1869 /* If command starts with 'rem ', ignore any &&, ( etc. */
1870 if (WCMD_keyword_ws_found(remCmd
, sizeof(remCmd
)/sizeof(remCmd
[0]), curPos
)) {
1873 } else if (WCMD_keyword_ws_found(forCmd
, sizeof(forCmd
)/sizeof(forCmd
[0]), curPos
)) {
1876 /* If command starts with 'if ' or 'else ', handle ('s mid line. We should ensure this
1877 is only true in the command portion of the IF statement, but this
1878 should suffice for now
1879 FIXME: Silly syntax like "if 1(==1( (
1881 )" will be parsed wrong */
1882 } else if (WCMD_keyword_ws_found(ifCmd
, sizeof(ifCmd
)/sizeof(ifCmd
[0]), curPos
)) {
1885 } else if (WCMD_keyword_ws_found(ifElse
, sizeof(ifElse
)/sizeof(ifElse
[0]), curPos
)) {
1886 const int keyw_len
= sizeof(ifElse
)/sizeof(ifElse
[0]) + 1;
1889 onlyWhiteSpace
= TRUE
;
1890 memcpy(&curCopyTo
[*curLen
], curPos
, keyw_len
*sizeof(WCHAR
));
1891 (*curLen
)+=keyw_len
;
1895 /* In a for loop, the DO command will follow a close bracket followed by
1896 whitespace, followed by DO, ie closeBracket inserts a NULL entry, curLen
1897 is then 0, and all whitespace is skipped */
1899 WCMD_keyword_ws_found(forDO
, sizeof(forDO
)/sizeof(forDO
[0]), curPos
)) {
1900 const int keyw_len
= sizeof(forDO
)/sizeof(forDO
[0]) + 1;
1901 WINE_TRACE("Found 'DO '\n");
1903 onlyWhiteSpace
= TRUE
;
1904 memcpy(&curCopyTo
[*curLen
], curPos
, keyw_len
*sizeof(WCHAR
));
1905 (*curLen
)+=keyw_len
;
1909 } else if (curCopyTo
== curString
) {
1911 /* Special handling for the 'FOR' command */
1912 if (inFor
&& lastWasWhiteSpace
) {
1913 static const WCHAR forIN
[] = {'i','n'};
1915 WINE_TRACE("Found 'FOR ', comparing next parm: '%s'\n", wine_dbgstr_w(curPos
));
1917 if (WCMD_keyword_ws_found(forIN
, sizeof(forIN
)/sizeof(forIN
[0]), curPos
)) {
1918 const int keyw_len
= sizeof(forIN
)/sizeof(forIN
[0]) + 1;
1919 WINE_TRACE("Found 'IN '\n");
1921 onlyWhiteSpace
= TRUE
;
1922 memcpy(&curCopyTo
[*curLen
], curPos
, keyw_len
*sizeof(WCHAR
));
1923 (*curLen
)+=keyw_len
;
1930 /* Nothing 'ends' a REM statement and &&, quotes etc are ineffective,
1931 so just use the default processing ie skip character specific
1933 if (!inRem
) thisChar
= *curPos
;
1934 else thisChar
= 'X'; /* Character with no special processing */
1936 lastWasWhiteSpace
= FALSE
; /* Will be reset below */
1940 case '=': /* drop through - ignore token delimiters at the start of a command */
1941 case ',': /* drop through - ignore token delimiters at the start of a command */
1942 case '\t':/* drop through - ignore token delimiters at the start of a command */
1944 /* If a redirect in place, it ends here */
1945 if (!inQuotes
&& !lastWasRedirect
) {
1947 /* If finishing off a redirect, add a whitespace delimiter */
1948 if (curCopyTo
== curRedirs
) {
1949 curCopyTo
[(*curLen
)++] = ' ';
1951 curCopyTo
= curString
;
1952 curLen
= &curStringLen
;
1955 curCopyTo
[(*curLen
)++] = *curPos
;
1958 /* Remember just processed whitespace */
1959 lastWasWhiteSpace
= TRUE
;
1963 case '>': /* drop through - handle redirect chars the same */
1965 /* Make a redirect start here */
1967 curCopyTo
= curRedirs
;
1968 curLen
= &curRedirsLen
;
1969 lastWasRedirect
= TRUE
;
1972 /* See if 1>, 2> etc, in which case we have some patching up
1973 to do (provided there's a preceding whitespace, and enough
1974 chars read so far) */
1975 if (curStringLen
> 2
1976 && (*(curPos
-1)>='1') && (*(curPos
-1)<='9')
1977 && ((*(curPos
-2)==' ') || (*(curPos
-2)=='\t'))) {
1979 curString
[curStringLen
] = 0x00;
1980 curCopyTo
[(*curLen
)++] = *(curPos
-1);
1983 curCopyTo
[(*curLen
)++] = *curPos
;
1985 /* If a redirect is immediately followed by '&' (ie. 2>&1) then
1986 do not process that ampersand as an AND operator */
1987 if (thisChar
== '>' && *(curPos
+1) == '&') {
1988 curCopyTo
[(*curLen
)++] = *(curPos
+1);
1993 case '|': /* Pipe character only if not || */
1995 lastWasRedirect
= FALSE
;
1997 /* Add an entry to the command list */
1998 if (curStringLen
> 0) {
2000 /* Add the current command */
2001 WCMD_addCommand(curString
, &curStringLen
,
2002 curRedirs
, &curRedirsLen
,
2003 &curCopyTo
, &curLen
,
2004 prevDelim
, curDepth
,
2005 &lastEntry
, output
);
2009 if (*(curPos
+1) == '|') {
2010 curPos
++; /* Skip other | */
2011 prevDelim
= CMD_ONFAILURE
;
2013 prevDelim
= CMD_PIPE
;
2016 curCopyTo
[(*curLen
)++] = *curPos
;
2020 case '"': if (WCMD_IsEndQuote(curPos
, inQuotes
)) {
2023 inQuotes
++; /* Quotes within quotes are fun! */
2025 curCopyTo
[(*curLen
)++] = *curPos
;
2026 lastWasRedirect
= FALSE
;
2029 case '(': /* If a '(' is the first non whitespace in a command portion
2030 ie start of line or just after &&, then we read until an
2031 unquoted ) is found */
2032 WINE_TRACE("Found '(' conditions: curLen(%d), inQ(%d), onlyWS(%d)"
2033 ", for(%d, In:%d, Do:%d)"
2034 ", if(%d, else:%d, lwe:%d)\n",
2037 inFor
, lastWasIn
, lastWasDo
,
2038 inIf
, inElse
, lastWasElse
);
2039 lastWasRedirect
= FALSE
;
2041 /* Ignore open brackets inside the for set */
2042 if (*curLen
== 0 && !inIn
) {
2045 /* If in quotes, ignore brackets */
2046 } else if (inQuotes
) {
2047 curCopyTo
[(*curLen
)++] = *curPos
;
2049 /* In a FOR loop, an unquoted '(' may occur straight after
2051 In an IF statement just handle it regardless as we don't
2053 In an ELSE statement, only allow it straight away after
2054 the ELSE and whitespace
2057 (inElse
&& lastWasElse
&& onlyWhiteSpace
) ||
2058 (inFor
&& (lastWasIn
|| lastWasDo
) && onlyWhiteSpace
)) {
2060 /* If entering into an 'IN', set inIn */
2061 if (inFor
&& lastWasIn
&& onlyWhiteSpace
) {
2062 WINE_TRACE("Inside an IN\n");
2066 /* Add the current command */
2067 WCMD_addCommand(curString
, &curStringLen
,
2068 curRedirs
, &curRedirsLen
,
2069 &curCopyTo
, &curLen
,
2070 prevDelim
, curDepth
,
2071 &lastEntry
, output
);
2075 curCopyTo
[(*curLen
)++] = *curPos
;
2079 case '&': if (!inQuotes
) {
2080 lastWasRedirect
= FALSE
;
2082 /* Add an entry to the command list */
2083 if (curStringLen
> 0) {
2085 /* Add the current command */
2086 WCMD_addCommand(curString
, &curStringLen
,
2087 curRedirs
, &curRedirsLen
,
2088 &curCopyTo
, &curLen
,
2089 prevDelim
, curDepth
,
2090 &lastEntry
, output
);
2094 if (*(curPos
+1) == '&') {
2095 curPos
++; /* Skip other & */
2096 prevDelim
= CMD_ONSUCCESS
;
2098 prevDelim
= CMD_NONE
;
2101 curCopyTo
[(*curLen
)++] = *curPos
;
2105 case ')': if (!inQuotes
&& curDepth
> 0) {
2106 lastWasRedirect
= FALSE
;
2108 /* Add the current command if there is one */
2111 /* Add the current command */
2112 WCMD_addCommand(curString
, &curStringLen
,
2113 curRedirs
, &curRedirsLen
,
2114 &curCopyTo
, &curLen
,
2115 prevDelim
, curDepth
,
2116 &lastEntry
, output
);
2119 /* Add an empty entry to the command list */
2120 prevDelim
= CMD_NONE
;
2121 WCMD_addCommand(NULL
, &curStringLen
,
2122 curRedirs
, &curRedirsLen
,
2123 &curCopyTo
, &curLen
,
2124 prevDelim
, curDepth
,
2125 &lastEntry
, output
);
2128 /* Leave inIn if necessary */
2129 if (inIn
) inIn
= FALSE
;
2131 curCopyTo
[(*curLen
)++] = *curPos
;
2135 lastWasRedirect
= FALSE
;
2136 curCopyTo
[(*curLen
)++] = *curPos
;
2141 /* At various times we need to know if we have only skipped whitespace,
2142 so reset this variable and then it will remain true until a non
2143 whitespace is found */
2144 if ((thisChar
!= ' ') && (thisChar
!= '\t') && (thisChar
!= '\n'))
2145 onlyWhiteSpace
= FALSE
;
2147 /* Flag end of interest in FOR DO and IN parms once something has been processed */
2148 if (!lastWasWhiteSpace
) {
2149 lastWasIn
= lastWasDo
= FALSE
;
2152 /* If we have reached the end, add this command into the list */
2153 if (*curPos
== 0x00 && *curLen
> 0) {
2155 /* Add an entry to the command list */
2156 WCMD_addCommand(curString
, &curStringLen
,
2157 curRedirs
, &curRedirsLen
,
2158 &curCopyTo
, &curLen
,
2159 prevDelim
, curDepth
,
2160 &lastEntry
, output
);
2163 /* If we have reached the end of the string, see if bracketing outstanding */
2164 if (*curPos
== 0x00 && curDepth
> 0 && readFrom
!= INVALID_HANDLE_VALUE
) {
2166 prevDelim
= CMD_NONE
;
2168 memset(extraSpace
, 0x00, (MAXSTRING
+1) * sizeof(WCHAR
));
2170 /* Read more, skipping any blank lines */
2171 while (*extraSpace
== 0x00) {
2172 if (!context
) WCMD_output_asis( WCMD_LoadMessage(WCMD_MOREPROMPT
));
2173 if (WCMD_fgets(extraSpace
, MAXSTRING
, readFrom
) == NULL
) break;
2175 curPos
= extraSpace
;
2176 if (context
) handleExpansion(extraSpace
, FALSE
, NULL
, NULL
);
2177 /* Continue to echo commands IF echo is on and in batch program */
2178 if (context
&& echo_mode
&& extraSpace
[0] && (extraSpace
[0] != '@')) {
2179 WCMD_output_asis(extraSpace
);
2180 WCMD_output_asis(newline
);
2185 /* Dump out the parsed output */
2186 WCMD_DumpCommands(*output
);
2191 /***************************************************************************
2192 * WCMD_process_commands
2194 * Process all the commands read in so far
2196 CMD_LIST
*WCMD_process_commands(CMD_LIST
*thisCmd
, BOOL oneBracket
,
2197 const WCHAR
*var
, const WCHAR
*val
) {
2201 if (thisCmd
&& oneBracket
) bdepth
= thisCmd
->bracketDepth
;
2203 /* Loop through the commands, processing them one by one */
2206 CMD_LIST
*origCmd
= thisCmd
;
2208 /* If processing one bracket only, and we find the end bracket
2209 entry (or less), return */
2210 if (oneBracket
&& !thisCmd
->command
&&
2211 bdepth
<= thisCmd
->bracketDepth
) {
2212 WINE_TRACE("Finished bracket @ %p, next command is %p\n",
2213 thisCmd
, thisCmd
->nextcommand
);
2214 return thisCmd
->nextcommand
;
2217 /* Ignore the NULL entries a ')' inserts (Only 'if' cares
2218 about them and it will be handled in there)
2219 Also, skip over any batch labels (eg. :fred) */
2220 if (thisCmd
->command
&& thisCmd
->command
[0] != ':') {
2221 WINE_TRACE("Executing command: '%s'\n", wine_dbgstr_w(thisCmd
->command
));
2222 WCMD_execute (thisCmd
->command
, thisCmd
->redirects
, var
, val
, &thisCmd
);
2225 /* Step on unless the command itself already stepped on */
2226 if (thisCmd
== origCmd
) thisCmd
= thisCmd
->nextcommand
;
2231 /***************************************************************************
2232 * WCMD_free_commands
2234 * Frees the storage held for a parsed command line
2235 * - This is not done in the process_commands, as eventually the current
2236 * pointer will be modified within the commands, and hence a single free
2237 * routine is simpler
2239 void WCMD_free_commands(CMD_LIST
*cmds
) {
2241 /* Loop through the commands, freeing them one by one */
2243 CMD_LIST
*thisCmd
= cmds
;
2244 cmds
= cmds
->nextcommand
;
2245 HeapFree(GetProcessHeap(), 0, thisCmd
->command
);
2246 HeapFree(GetProcessHeap(), 0, thisCmd
->redirects
);
2247 HeapFree(GetProcessHeap(), 0, thisCmd
);
2252 /*****************************************************************************
2253 * Main entry point. This is a console application so we have a main() not a
2257 int wmain (int argc
, WCHAR
*argvW
[])
2265 static const WCHAR promptW
[] = {'P','R','O','M','P','T','\0'};
2266 static const WCHAR defaultpromptW
[] = {'$','P','$','G','\0'};
2267 char ansiVersion
[100];
2268 CMD_LIST
*toExecute
= NULL
; /* Commands left to be executed */
2272 /* Pre initialize some messages */
2273 strcpy(ansiVersion
, PACKAGE_VERSION
);
2274 MultiByteToWideChar(CP_ACP
, 0, ansiVersion
, -1, string
, 1024);
2275 wsprintfW(version_string
, WCMD_LoadMessage(WCMD_VERSION
), string
);
2276 strcpyW(anykey
, WCMD_LoadMessage(WCMD_ANYKEY
));
2279 opt_c
=opt_k
=opt_q
=opt_s
=0;
2283 WINE_TRACE("Command line parm: '%s'\n", wine_dbgstr_w(*argvW
));
2284 if ((*argvW
)[0]!='/' || (*argvW
)[1]=='\0') {
2291 if (tolowerW(c
)=='c') {
2293 } else if (tolowerW(c
)=='q') {
2295 } else if (tolowerW(c
)=='k') {
2297 } else if (tolowerW(c
)=='s') {
2299 } else if (tolowerW(c
)=='a') {
2301 } else if (tolowerW(c
)=='u') {
2303 } else if (tolowerW(c
)=='t' && (*argvW
)[2]==':') {
2304 opt_t
=strtoulW(&(*argvW
)[3], NULL
, 16);
2305 } else if (tolowerW(c
)=='x' || tolowerW(c
)=='y') {
2306 /* Ignored for compatibility with Windows */
2309 if ((*argvW
)[2]==0) {
2313 else /* handle `cmd /cnotepad.exe` and `cmd /x/c ...` */
2318 if (opt_c
|| opt_k
) /* break out of parsing immediately after c or k */
2323 static const WCHAR eoff
[] = {'O','F','F','\0'};
2327 if (opt_c
|| opt_k
) {
2333 /* opt_s left unflagged if the command starts with and contains exactly
2334 * one quoted string (exactly two quote characters). The quoted string
2335 * must be an executable name that has whitespace and must not have the
2336 * following characters: &<>()@^| */
2338 /* Build the command to execute */
2342 for (arg
= argvW
; argsLeft
>0; arg
++,argsLeft
--)
2344 int has_space
,bcount
;
2350 if( !*a
) has_space
=1;
2355 if (*a
==' ' || *a
=='\t') {
2357 } else if (*a
=='"') {
2358 /* doubling of '\' preceding a '"',
2359 * plus escaping of said '"'
2368 len
+=(a
-*arg
) + 1; /* for the separating space */
2371 len
+=2; /* for the quotes */
2379 /* check argvW[0] for a space and invalid characters */
2384 if (*p
=='&' || *p
=='<' || *p
=='>' || *p
=='(' || *p
==')'
2385 || *p
=='@' || *p
=='^' || *p
=='|') {
2395 cmd
= HeapAlloc(GetProcessHeap(), 0, len
* sizeof(WCHAR
));
2401 for (arg
= argvW
; argsLeft
>0; arg
++,argsLeft
--)
2403 int has_space
,has_quote
;
2406 /* Check for quotes and spaces in this argument */
2407 has_space
=has_quote
=0;
2409 if( !*a
) has_space
=1;
2411 if (*a
==' ' || *a
=='\t') {
2415 } else if (*a
=='"') {
2423 /* Now transfer it to the command line */
2440 /* Double all the '\\' preceding this '"', plus one */
2441 for (i
=0;i
<=bcount
;i
++)
2460 p
--; /* remove last space */
2463 WINE_TRACE("/c command line: '%s'\n", wine_dbgstr_w(cmd
));
2465 /* strip first and last quote characters if opt_s; check for invalid
2466 * executable is done later */
2467 if (opt_s
&& *cmd
=='\"')
2468 WCMD_opt_s_strip_quotes(cmd
);
2472 /* If we do a "cmd /c command", we don't want to allocate a new
2473 * console since the command returns immediately. Rather, we use
2474 * the currently allocated input and output handles. This allows
2475 * us to pipe to and read from the command interpreter.
2478 /* Parse the command string, without reading any more input */
2479 WCMD_ReadAndParseLine(cmd
, &toExecute
, INVALID_HANDLE_VALUE
);
2480 WCMD_process_commands(toExecute
, FALSE
, NULL
, NULL
);
2481 WCMD_free_commands(toExecute
);
2484 HeapFree(GetProcessHeap(), 0, cmd
);
2488 SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE
), ENABLE_LINE_INPUT
|
2489 ENABLE_ECHO_INPUT
| ENABLE_PROCESSED_INPUT
);
2490 SetConsoleTitleW(WCMD_LoadMessage(WCMD_CONSTITLE
));
2492 /* Note: cmd.exe /c dir does not get a new color, /k dir does */
2494 if (!(((opt_t
& 0xF0) >> 4) == (opt_t
& 0x0F))) {
2495 defaultColor
= opt_t
& 0xFF;
2500 /* Check HKCU\Software\Microsoft\Command Processor
2501 Then HKLM\Software\Microsoft\Command Processor
2502 for defaultcolour value
2503 Note Can be supplied as DWORD or REG_SZ
2504 Note2 When supplied as REG_SZ it's in decimal!!! */
2507 DWORD value
=0, size
=4;
2508 static const WCHAR regKeyW
[] = {'S','o','f','t','w','a','r','e','\\',
2509 'M','i','c','r','o','s','o','f','t','\\',
2510 'C','o','m','m','a','n','d',' ','P','r','o','c','e','s','s','o','r','\0'};
2511 static const WCHAR dfltColorW
[] = {'D','e','f','a','u','l','t','C','o','l','o','r','\0'};
2513 if (RegOpenKeyExW(HKEY_CURRENT_USER
, regKeyW
,
2514 0, KEY_READ
, &key
) == ERROR_SUCCESS
) {
2517 /* See if DWORD or REG_SZ */
2518 if (RegQueryValueExW(key
, dfltColorW
, NULL
, &type
,
2519 NULL
, NULL
) == ERROR_SUCCESS
) {
2520 if (type
== REG_DWORD
) {
2521 size
= sizeof(DWORD
);
2522 RegQueryValueExW(key
, dfltColorW
, NULL
, NULL
,
2523 (LPBYTE
)&value
, &size
);
2524 } else if (type
== REG_SZ
) {
2525 size
= sizeof(strvalue
)/sizeof(WCHAR
);
2526 RegQueryValueExW(key
, dfltColorW
, NULL
, NULL
,
2527 (LPBYTE
)strvalue
, &size
);
2528 value
= strtoulW(strvalue
, NULL
, 10);
2534 if (value
== 0 && RegOpenKeyExW(HKEY_LOCAL_MACHINE
, 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 one found, set the screen to that colour */
2556 if (!(((value
& 0xF0) >> 4) == (value
& 0x0F))) {
2557 defaultColor
= value
& 0xFF;
2564 /* Save cwd into appropriate env var */
2565 GetCurrentDirectoryW(1024, string
);
2566 if (IsCharAlphaW(string
[0]) && string
[1] == ':') {
2567 static const WCHAR fmt
[] = {'=','%','c',':','\0'};
2568 wsprintfW(envvar
, fmt
, string
[0]);
2569 SetEnvironmentVariableW(envvar
, string
);
2570 WINE_TRACE("Set %s to %s\n", wine_dbgstr_w(envvar
), wine_dbgstr_w(string
));
2574 /* Parse the command string, without reading any more input */
2575 WCMD_ReadAndParseLine(cmd
, &toExecute
, INVALID_HANDLE_VALUE
);
2576 WCMD_process_commands(toExecute
, FALSE
, NULL
, NULL
);
2577 WCMD_free_commands(toExecute
);
2579 HeapFree(GetProcessHeap(), 0, cmd
);
2583 * Loop forever getting commands and executing them.
2586 SetEnvironmentVariableW(promptW
, defaultpromptW
);
2590 /* Read until EOF (which for std input is never, but if redirect
2591 in place, may occur */
2592 if (echo_mode
) WCMD_show_prompt();
2593 if (WCMD_ReadAndParseLine(NULL
, &toExecute
,
2594 GetStdHandle(STD_INPUT_HANDLE
)) == NULL
)
2596 WCMD_process_commands(toExecute
, FALSE
, NULL
, NULL
);
2597 WCMD_free_commands(toExecute
);