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
32 #include "wine/debug.h"
34 WINE_DEFAULT_DEBUG_CHANNEL(cmd
);
36 extern const WCHAR inbuilt
[][10];
37 extern struct env_stack
*pushd_directories
;
39 BATCH_CONTEXT
*context
= NULL
;
41 WCHAR quals
[MAX_PATH
], param1
[MAXSTRING
], param2
[MAXSTRING
];
43 FOR_CONTEXT forloopcontext
; /* The 'for' loop context */
44 BOOL delayedsubst
= FALSE
; /* The current delayed substitution setting */
47 BOOL echo_mode
= TRUE
;
49 WCHAR anykey
[100], version_string
[100];
50 const WCHAR newlineW
[] = {'\r','\n','\0'};
51 const WCHAR spaceW
[] = {' ','\0'};
52 static const WCHAR envPathExt
[] = {'P','A','T','H','E','X','T','\0'};
53 static const WCHAR dfltPathExt
[] = {'.','b','a','t',';',
56 '.','e','x','e','\0'};
58 static BOOL opt_c
, opt_k
, opt_s
, unicodeOutput
= FALSE
;
60 /* Variables pertaining to paging */
61 static BOOL paged_mode
;
62 static const WCHAR
*pagedMessage
= NULL
;
63 static int line_count
;
64 static int max_height
;
68 #define MAX_WRITECONSOLE_SIZE 65535
71 * Returns a buffer for reading from/writing to file
74 static char *get_file_buffer(void)
76 static char *output_bufA
= NULL
;
78 output_bufA
= heap_alloc(MAX_WRITECONSOLE_SIZE
);
82 /*******************************************************************
83 * WCMD_output_asis_len - send output to current standard output
85 * Output a formatted unicode string. Ideally this will go to the console
86 * and hence required WriteConsoleW to output it, however if file i/o is
87 * redirected, it needs to be WriteFile'd using OEM (not ANSI) format
89 static void WCMD_output_asis_len(const WCHAR
*message
, DWORD len
, HANDLE device
)
94 /* If nothing to write, return (MORE does this sometimes) */
97 /* Try to write as unicode assuming it is to a console */
98 res
= WriteConsoleW(device
, message
, len
, &nOut
, NULL
);
100 /* If writing to console fails, assume it's file
101 i/o so convert to OEM codepage and output */
103 BOOL usedDefaultChar
= FALSE
;
104 DWORD convertedChars
;
107 if (!unicodeOutput
) {
109 if (!(buffer
= get_file_buffer()))
112 /* Convert to OEM, then output */
113 convertedChars
= WideCharToMultiByte(GetConsoleOutputCP(), 0, message
,
114 len
, buffer
, MAX_WRITECONSOLE_SIZE
,
115 "?", &usedDefaultChar
);
116 WriteFile(device
, buffer
, convertedChars
,
119 WriteFile(device
, message
, len
*sizeof(WCHAR
),
126 /*******************************************************************
127 * WCMD_output - send output to current standard output device.
131 void WINAPIV
WCMD_output (const WCHAR
*format
, ...) {
137 __ms_va_start(ap
,format
);
138 SetLastError(NO_ERROR
);
140 len
= FormatMessageW(FORMAT_MESSAGE_FROM_STRING
|FORMAT_MESSAGE_ALLOCATE_BUFFER
,
141 format
, 0, 0, (LPWSTR
)&string
, 0, &ap
);
143 if (len
== 0 && GetLastError() != NO_ERROR
)
144 WINE_FIXME("Could not format string: le=%u, fmt=%s\n", GetLastError(), wine_dbgstr_w(format
));
147 WCMD_output_asis_len(string
, len
, GetStdHandle(STD_OUTPUT_HANDLE
));
152 /*******************************************************************
153 * WCMD_output_stderr - send output to current standard error device.
157 void WINAPIV
WCMD_output_stderr (const WCHAR
*format
, ...) {
163 __ms_va_start(ap
,format
);
164 SetLastError(NO_ERROR
);
166 len
= FormatMessageW(FORMAT_MESSAGE_FROM_STRING
|FORMAT_MESSAGE_ALLOCATE_BUFFER
,
167 format
, 0, 0, (LPWSTR
)&string
, 0, &ap
);
169 if (len
== 0 && GetLastError() != NO_ERROR
)
170 WINE_FIXME("Could not format string: le=%u, fmt=%s\n", GetLastError(), wine_dbgstr_w(format
));
173 WCMD_output_asis_len(string
, len
, GetStdHandle(STD_ERROR_HANDLE
));
178 /*******************************************************************
179 * WCMD_format_string - allocate a buffer and format a string
183 WCHAR
* WINAPIV
WCMD_format_string (const WCHAR
*format
, ...)
189 __ms_va_start(ap
,format
);
190 SetLastError(NO_ERROR
);
191 len
= FormatMessageW(FORMAT_MESSAGE_FROM_STRING
|FORMAT_MESSAGE_ALLOCATE_BUFFER
,
192 format
, 0, 0, (LPWSTR
)&string
, 0, &ap
);
194 if (len
== 0 && GetLastError() != NO_ERROR
) {
195 WINE_FIXME("Could not format string: le=%u, fmt=%s\n", GetLastError(), wine_dbgstr_w(format
));
196 string
= (WCHAR
*)LocalAlloc(LMEM_FIXED
, 2);
202 void WCMD_enter_paged_mode(const WCHAR
*msg
)
204 CONSOLE_SCREEN_BUFFER_INFO consoleInfo
;
206 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE
), &consoleInfo
)) {
207 max_height
= consoleInfo
.dwSize
.Y
;
208 max_width
= consoleInfo
.dwSize
.X
;
216 pagedMessage
= (msg
==NULL
)? anykey
: msg
;
219 void WCMD_leave_paged_mode(void)
225 /***************************************************************************
228 * Read characters in from a console/file, returning result in Unicode
230 BOOL
WCMD_ReadFile(const HANDLE hIn
, WCHAR
*intoBuf
, const DWORD maxChars
, LPDWORD charsRead
)
235 if (WCMD_is_console_handle(hIn
))
236 /* Try to read from console as Unicode */
237 return ReadConsoleW(hIn
, intoBuf
, maxChars
, charsRead
, NULL
);
239 /* We assume it's a file handle and read then convert from assumed OEM codepage */
240 if (!(buffer
= get_file_buffer()))
243 if (!ReadFile(hIn
, buffer
, maxChars
, &numRead
, NULL
))
246 *charsRead
= MultiByteToWideChar(GetConsoleCP(), 0, buffer
, numRead
, intoBuf
, maxChars
);
251 /*******************************************************************
252 * WCMD_output_asis_handle
254 * Send output to specified handle without formatting e.g. when message contains '%'
256 static void WCMD_output_asis_handle (DWORD std_handle
, const WCHAR
*message
) {
260 HANDLE handle
= GetStdHandle(std_handle
);
265 while (*ptr
&& *ptr
!='\n' && (numChars
< max_width
)) {
269 if (*ptr
== '\n') ptr
++;
270 WCMD_output_asis_len(message
, ptr
- 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
, sizeof(string
)/sizeof(WCHAR
), &count
);
277 } while (((message
= ptr
) != NULL
) && (*ptr
));
279 WCMD_output_asis_len(message
, lstrlenW(message
), handle
);
283 /*******************************************************************
286 * Send output to current standard output device, without formatting
287 * e.g. when message contains '%'
289 void WCMD_output_asis (const WCHAR
*message
) {
290 WCMD_output_asis_handle(STD_OUTPUT_HANDLE
, message
);
293 /*******************************************************************
294 * WCMD_output_asis_stderr
296 * Send output to current standard error device, without formatting
297 * e.g. when message contains '%'
299 void WCMD_output_asis_stderr (const WCHAR
*message
) {
300 WCMD_output_asis_handle(STD_ERROR_HANDLE
, message
);
303 /****************************************************************************
306 * Print the message for GetLastError
309 void WCMD_print_error (void) {
314 error_code
= GetLastError ();
315 status
= FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
,
316 NULL
, error_code
, 0, (LPWSTR
) &lpMsgBuf
, 0, NULL
);
318 WINE_FIXME ("Cannot display message for error %d, status %d\n",
319 error_code
, GetLastError());
323 WCMD_output_asis_len(lpMsgBuf
, lstrlenW(lpMsgBuf
),
324 GetStdHandle(STD_ERROR_HANDLE
));
325 LocalFree (lpMsgBuf
);
326 WCMD_output_asis_len (newlineW
, lstrlenW(newlineW
),
327 GetStdHandle(STD_ERROR_HANDLE
));
331 /******************************************************************************
334 * Display the prompt on STDout
338 static void WCMD_show_prompt (void) {
341 WCHAR out_string
[MAX_PATH
], curdir
[MAX_PATH
], prompt_string
[MAX_PATH
];
344 static const WCHAR envPrompt
[] = {'P','R','O','M','P','T','\0'};
346 len
= GetEnvironmentVariableW(envPrompt
, prompt_string
,
347 sizeof(prompt_string
)/sizeof(WCHAR
));
348 if ((len
== 0) || (len
>= (sizeof(prompt_string
)/sizeof(WCHAR
)))) {
349 static const WCHAR dfltPrompt
[] = {'$','P','$','G','\0'};
350 strcpyW (prompt_string
, dfltPrompt
);
364 switch (toupper(*p
)) {
378 GetDateFormatW(LOCALE_USER_DEFAULT
, DATE_SHORTDATE
, NULL
, NULL
, q
, MAX_PATH
- (q
- out_string
));
397 status
= GetCurrentDirectoryW(sizeof(curdir
)/sizeof(WCHAR
), curdir
);
403 status
= GetCurrentDirectoryW(sizeof(curdir
)/sizeof(WCHAR
), curdir
);
416 GetTimeFormatW(LOCALE_USER_DEFAULT
, 0, NULL
, NULL
, q
, MAX_PATH
);
420 strcatW (q
, version_string
);
427 if (pushd_directories
) {
428 memset(q
, '+', pushd_directories
->u
.stackdepth
);
429 q
= q
+ pushd_directories
->u
.stackdepth
;
437 WCMD_output_asis (out_string
);
440 void *heap_alloc(size_t size
)
444 ret
= HeapAlloc(GetProcessHeap(), 0, size
);
446 ERR("Out of memory\n");
453 /*************************************************************************
455 * Replaces a portion of a Unicode string with the specified string.
456 * It's up to the caller to ensure there is enough space in the
457 * destination buffer.
459 void WCMD_strsubstW(WCHAR
*start
, const WCHAR
*next
, const WCHAR
*insert
, int len
) {
462 len
=insert
? lstrlenW(insert
) : 0;
463 if (start
+len
!= next
)
464 memmove(start
+len
, next
, (strlenW(next
) + 1) * sizeof(*next
));
466 memcpy(start
, insert
, len
* sizeof(*insert
));
469 /***************************************************************************
470 * WCMD_skip_leading_spaces
472 * Return a pointer to the first non-whitespace character of string.
473 * Does not modify the input string.
475 WCHAR
*WCMD_skip_leading_spaces (WCHAR
*string
) {
480 while (*ptr
== ' ' || *ptr
== '\t') ptr
++;
484 /***************************************************************************
485 * WCMD_keyword_ws_found
487 * Checks if the string located at ptr matches a keyword (of length len)
488 * followed by a whitespace character (space or tab)
490 BOOL
WCMD_keyword_ws_found(const WCHAR
*keyword
, int len
, const WCHAR
*ptr
) {
491 return (CompareStringW(LOCALE_USER_DEFAULT
, NORM_IGNORECASE
| SORT_STRINGSORT
,
492 ptr
, len
, keyword
, len
) == CSTR_EQUAL
)
493 && ((*(ptr
+ len
) == ' ') || (*(ptr
+ len
) == '\t'));
496 /*************************************************************************
499 * Remove first and last quote WCHARacters, preserving all other text
500 * Returns the location of the final quote
502 WCHAR
*WCMD_strip_quotes(WCHAR
*cmd
) {
503 WCHAR
*src
= cmd
+ 1, *dest
= cmd
, *lastq
= NULL
, *lastquote
;
504 while((*dest
=*src
) != '\0') {
512 while ((*dest
++=*lastq
++) != 0)
519 /*************************************************************************
520 * WCMD_is_magic_envvar
521 * Return TRUE if s is '%'magicvar'%'
522 * and is not masked by a real environment variable.
525 static inline BOOL
WCMD_is_magic_envvar(const WCHAR
*s
, const WCHAR
*magicvar
)
530 return FALSE
; /* Didn't begin with % */
532 if (len
< 2 || s
[len
-1] != '%')
533 return FALSE
; /* Didn't end with another % */
535 if (CompareStringW(LOCALE_USER_DEFAULT
,
536 NORM_IGNORECASE
| SORT_STRINGSORT
,
537 s
+1, len
-2, magicvar
, -1) != CSTR_EQUAL
) {
538 /* Name doesn't match. */
542 if (GetEnvironmentVariableW(magicvar
, NULL
, 0) > 0) {
543 /* Masked by real environment variable. */
550 /*************************************************************************
553 * Expands environment variables, allowing for WCHARacter substitution
555 static WCHAR
*WCMD_expand_envvar(WCHAR
*start
, WCHAR startchar
)
557 WCHAR
*endOfVar
= NULL
, *s
;
558 WCHAR
*colonpos
= NULL
;
559 WCHAR thisVar
[MAXSTRING
];
560 WCHAR thisVarContents
[MAXSTRING
];
561 WCHAR savedchar
= 0x00;
564 static const WCHAR ErrorLvl
[] = {'E','R','R','O','R','L','E','V','E','L','\0'};
565 static const WCHAR Date
[] = {'D','A','T','E','\0'};
566 static const WCHAR Time
[] = {'T','I','M','E','\0'};
567 static const WCHAR Cd
[] = {'C','D','\0'};
568 static const WCHAR Random
[] = {'R','A','N','D','O','M','\0'};
569 WCHAR Delims
[] = {'%',':','\0'}; /* First char gets replaced appropriately */
571 WINE_TRACE("Expanding: %s (%c)\n", wine_dbgstr_w(start
), startchar
);
573 /* Find the end of the environment variable, and extract name */
574 Delims
[0] = startchar
;
575 endOfVar
= strpbrkW(start
+1, Delims
);
577 if (endOfVar
== NULL
|| *endOfVar
==' ') {
579 /* In batch program, missing terminator for % and no following
580 ':' just removes the '%' */
582 WCMD_strsubstW(start
, start
+ 1, NULL
, 0);
586 /* In command processing, just ignore it - allows command line
587 syntax like: for %i in (a.a) do echo %i */
592 /* If ':' found, process remaining up until '%' (or stop at ':' if
594 if (*endOfVar
==':') {
595 WCHAR
*endOfVar2
= strchrW(endOfVar
+1, startchar
);
596 if (endOfVar2
!= NULL
) endOfVar
= endOfVar2
;
599 memcpy(thisVar
, start
, ((endOfVar
- start
) + 1) * sizeof(WCHAR
));
600 thisVar
[(endOfVar
- start
)+1] = 0x00;
601 colonpos
= strchrW(thisVar
+1, ':');
603 /* If there's complex substitution, just need %var% for now
604 to get the expanded data to play with */
606 *colonpos
= startchar
;
607 savedchar
= *(colonpos
+1);
608 *(colonpos
+1) = 0x00;
611 /* By now, we know the variable we want to expand but it may be
612 surrounded by '!' if we are in delayed expansion - if so convert
614 if (startchar
=='!') {
616 thisVar
[(endOfVar
- start
)] = '%';
618 WINE_TRACE("Retrieving contents of %s\n", wine_dbgstr_w(thisVar
));
620 /* Expand to contents, if unchanged, return */
621 /* Handle DATE, TIME, ERRORLEVEL and CD replacements allowing */
622 /* override if existing env var called that name */
623 if (WCMD_is_magic_envvar(thisVar
, ErrorLvl
)) {
624 static const WCHAR fmt
[] = {'%','d','\0'};
625 wsprintfW(thisVarContents
, fmt
, errorlevel
);
626 len
= strlenW(thisVarContents
);
627 } else if (WCMD_is_magic_envvar(thisVar
, Date
)) {
628 GetDateFormatW(LOCALE_USER_DEFAULT
, DATE_SHORTDATE
, NULL
,
629 NULL
, thisVarContents
, MAXSTRING
);
630 len
= strlenW(thisVarContents
);
631 } else if (WCMD_is_magic_envvar(thisVar
, Time
)) {
632 GetTimeFormatW(LOCALE_USER_DEFAULT
, TIME_NOSECONDS
, NULL
,
633 NULL
, thisVarContents
, MAXSTRING
);
634 len
= strlenW(thisVarContents
);
635 } else if (WCMD_is_magic_envvar(thisVar
, Cd
)) {
636 GetCurrentDirectoryW(MAXSTRING
, thisVarContents
);
637 len
= strlenW(thisVarContents
);
638 } else if (WCMD_is_magic_envvar(thisVar
, Random
)) {
639 static const WCHAR fmt
[] = {'%','d','\0'};
640 wsprintfW(thisVarContents
, fmt
, rand() % 32768);
641 len
= strlenW(thisVarContents
);
644 len
= ExpandEnvironmentStringsW(thisVar
, thisVarContents
,
645 sizeof(thisVarContents
)/sizeof(WCHAR
));
651 /* In a batch program, unknown env vars are replaced with nothing,
652 note syntax %garbage:1,3% results in anything after the ':'
654 From the command line, you just get back what you entered */
655 if (lstrcmpiW(thisVar
, thisVarContents
) == 0) {
657 /* Restore the complex part after the compare */
660 *(colonpos
+1) = savedchar
;
663 /* Command line - just ignore this */
664 if (context
== NULL
) return endOfVar
+1;
667 /* Batch - replace unknown env var with nothing */
668 if (colonpos
== NULL
) {
669 WCMD_strsubstW(start
, endOfVar
+ 1, NULL
, 0);
671 len
= strlenW(thisVar
);
672 thisVar
[len
-1] = 0x00;
673 /* If %:...% supplied, : is retained */
674 if (colonpos
== thisVar
+1) {
675 WCMD_strsubstW(start
, endOfVar
+ 1, colonpos
, -1);
677 WCMD_strsubstW(start
, endOfVar
+ 1, colonpos
+ 1, -1);
684 /* See if we need to do complex substitution (any ':'s), if not
685 then our work here is done */
686 if (colonpos
== NULL
) {
687 WCMD_strsubstW(start
, endOfVar
+ 1, thisVarContents
, -1);
691 /* Restore complex bit */
693 *(colonpos
+1) = savedchar
;
696 Handle complex substitutions:
697 xxx=yyy (replace xxx with yyy)
698 *xxx=yyy (replace up to and including xxx with yyy)
699 ~x (from x WCHARs in)
700 ~-x (from x WCHARs from the end)
701 ~x,y (from x WCHARs in for y WCHARacters)
702 ~x,-y (from x WCHARs in until y WCHARacters from the end)
705 /* ~ is substring manipulation */
706 if (savedchar
== '~') {
708 int substrposition
, substrlength
= 0;
709 WCHAR
*commapos
= strchrW(colonpos
+2, ',');
712 substrposition
= atolW(colonpos
+2);
713 if (commapos
) substrlength
= atolW(commapos
+1);
716 if (substrposition
>= 0) {
717 startCopy
= &thisVarContents
[min(substrposition
, len
)];
719 startCopy
= &thisVarContents
[max(0, len
+substrposition
-1)];
722 if (commapos
== NULL
) {
724 WCMD_strsubstW(start
, endOfVar
+ 1, startCopy
, -1);
725 } else if (substrlength
< 0) {
727 int copybytes
= (len
+substrlength
-1)-(startCopy
-thisVarContents
);
728 if (copybytes
> len
) copybytes
= len
;
729 else if (copybytes
< 0) copybytes
= 0;
730 WCMD_strsubstW(start
, endOfVar
+ 1, startCopy
, copybytes
);
732 substrlength
= min(substrlength
, len
- (startCopy
- thisVarContents
+ 1));
733 WCMD_strsubstW(start
, endOfVar
+ 1, startCopy
, substrlength
);
736 /* search and replace manipulation */
738 WCHAR
*equalspos
= strstrW(colonpos
, equalW
);
739 WCHAR
*replacewith
= equalspos
+1;
744 if (equalspos
== NULL
) return start
+1;
745 s
= heap_strdupW(endOfVar
+ 1);
747 /* Null terminate both strings */
748 thisVar
[strlenW(thisVar
)-1] = 0x00;
751 /* Since we need to be case insensitive, copy the 2 buffers */
752 searchIn
= heap_strdupW(thisVarContents
);
753 CharUpperBuffW(searchIn
, strlenW(thisVarContents
));
754 searchFor
= heap_strdupW(colonpos
+1);
755 CharUpperBuffW(searchFor
, strlenW(colonpos
+1));
757 /* Handle wildcard case */
758 if (*(colonpos
+1) == '*') {
759 /* Search for string to replace */
760 found
= strstrW(searchIn
, searchFor
+1);
764 strcpyW(start
, replacewith
);
765 strcatW(start
, thisVarContents
+ (found
-searchIn
) + strlenW(searchFor
+1));
769 strcpyW(start
, thisVarContents
);
774 /* Loop replacing all instances */
775 WCHAR
*lastFound
= searchIn
;
776 WCHAR
*outputposn
= start
;
779 while ((found
= strstrW(lastFound
, searchFor
))) {
780 lstrcpynW(outputposn
,
781 thisVarContents
+ (lastFound
-searchIn
),
782 (found
- lastFound
)+1);
783 outputposn
= outputposn
+ (found
- lastFound
);
784 strcatW(outputposn
, replacewith
);
785 outputposn
= outputposn
+ strlenW(replacewith
);
786 lastFound
= found
+ strlenW(searchFor
);
789 thisVarContents
+ (lastFound
-searchIn
));
790 strcatW(outputposn
, s
);
794 heap_free(searchFor
);
799 /*****************************************************************************
800 * Expand the command. Native expands lines from batch programs as they are
801 * read in and not again, except for 'for' variable substitution.
802 * eg. As evidence, "echo %1 && shift && echo %1" or "echo %%path%%"
803 * atExecute is TRUE when the expansion is occurring as the command is executed
804 * rather than at parse time, i.e. delayed expansion and for loops need to be
807 static void handleExpansion(WCHAR
*cmd
, BOOL atExecute
, BOOL delayed
) {
809 /* For commands in a context (batch program): */
810 /* Expand environment variables in a batch file %{0-9} first */
811 /* including support for any ~ modifiers */
813 /* Expand the DATE, TIME, CD, RANDOM and ERRORLEVEL special */
814 /* names allowing environment variable overrides */
815 /* NOTE: To support the %PATH:xxx% syntax, also perform */
816 /* manual expansion of environment variables here */
821 WCHAR
*delayedp
= NULL
;
822 WCHAR startchar
= '%';
825 /* Display the FOR variables in effect */
827 if (forloopcontext
.variable
[i
]) {
828 WINE_TRACE("FOR variable context: %c = '%s'\n",
829 i
<26?i
+'a':(i
-26)+'A',
830 wine_dbgstr_w(forloopcontext
.variable
[i
]));
834 /* Find the next environment variable delimiter */
835 normalp
= strchrW(p
, '%');
836 if (delayed
) delayedp
= strchrW(p
, '!');
837 if (!normalp
) p
= delayedp
;
838 else if (!delayedp
) p
= normalp
;
839 else p
= min(p
,delayedp
);
840 if (p
) startchar
= *p
;
844 WINE_TRACE("Translate command:%s %d (at: %s)\n",
845 wine_dbgstr_w(cmd
), atExecute
, wine_dbgstr_w(p
));
848 /* Don't touch %% unless it's in Batch */
849 if (!atExecute
&& *(p
+1) == startchar
) {
851 WCMD_strsubstW(p
, p
+1, NULL
, 0);
855 /* Replace %~ modifications if in batch program */
856 } else if (*(p
+1) == '~') {
857 WCMD_HandleTildaModifiers(&p
, atExecute
);
860 /* Replace use of %0...%9 if in batch program*/
861 } else if (!atExecute
&& context
&& (i
>= 0) && (i
<= 9) && startchar
== '%') {
862 t
= WCMD_parameter(context
-> command
, i
+ context
-> shift_count
[i
],
864 WCMD_strsubstW(p
, p
+2, t
, -1);
866 /* Replace use of %* if in batch program*/
867 } else if (!atExecute
&& context
&& *(p
+1)=='*' && startchar
== '%') {
868 WCHAR
*startOfParms
= NULL
;
869 WCHAR
*thisParm
= WCMD_parameter(context
-> command
, 0, &startOfParms
, TRUE
, TRUE
);
870 if (startOfParms
!= NULL
) {
871 startOfParms
+= strlenW(thisParm
);
872 while (*startOfParms
==' ' || *startOfParms
== '\t') startOfParms
++;
873 WCMD_strsubstW(p
, p
+2, startOfParms
, -1);
875 WCMD_strsubstW(p
, p
+2, NULL
, 0);
878 int forvaridx
= FOR_VAR_IDX(*(p
+1));
879 if (startchar
== '%' && forvaridx
!= -1 && forloopcontext
.variable
[forvaridx
]) {
880 /* Replace the 2 characters, % and for variable character */
881 WCMD_strsubstW(p
, p
+ 2, forloopcontext
.variable
[forvaridx
], -1);
882 } else if (!atExecute
|| startchar
== '!') {
883 p
= WCMD_expand_envvar(p
, startchar
);
885 /* In a FOR loop, see if this is the variable to replace */
886 } else { /* Ignore %'s on second pass of batch program */
891 /* Find the next environment variable delimiter */
892 normalp
= strchrW(p
, '%');
893 if (delayed
) delayedp
= strchrW(p
, '!');
894 if (!normalp
) p
= delayedp
;
895 else if (!delayedp
) p
= normalp
;
896 else p
= min(p
,delayedp
);
897 if (p
) startchar
= *p
;
904 /*******************************************************************
905 * WCMD_parse - parse a command into parameters and qualifiers.
907 * On exit, all qualifiers are concatenated into q, the first string
908 * not beginning with "/" is in p1 and the
909 * second in p2. Any subsequent non-qualifier strings are lost.
910 * Parameters in quotes are handled.
912 static void WCMD_parse (const WCHAR
*s
, WCHAR
*q
, WCHAR
*p1
, WCHAR
*p2
)
916 *q
= *p1
= *p2
= '\0';
921 while ((*s
!= '\0') && (*s
!= ' ') && *s
!= '/') {
922 *q
++ = toupperW (*s
++);
932 while ((*s
!= '\0') && (*s
!= '"')) {
933 if (p
== 0) *p1
++ = *s
++;
934 else if (p
== 1) *p2
++ = *s
++;
937 if (p
== 0) *p1
= '\0';
938 if (p
== 1) *p2
= '\0';
945 while ((*s
!= '\0') && (*s
!= ' ') && (*s
!= '\t')
946 && (*s
!= '=') && (*s
!= ',') ) {
947 if (p
== 0) *p1
++ = *s
++;
948 else if (p
== 1) *p2
++ = *s
++;
951 /* Skip concurrent parms */
952 while ((*s
== ' ') || (*s
== '\t') || (*s
== '=') || (*s
== ',') ) s
++;
954 if (p
== 0) *p1
= '\0';
955 if (p
== 1) *p2
= '\0';
961 static void init_msvcrt_io_block(STARTUPINFOW
* st
)
964 /* fetch the parent MSVCRT info block if any, so that the child can use the
965 * same handles as its grand-father
967 st_p
.cb
= sizeof(STARTUPINFOW
);
968 GetStartupInfoW(&st_p
);
969 st
->cbReserved2
= st_p
.cbReserved2
;
970 st
->lpReserved2
= st_p
.lpReserved2
;
971 if (st_p
.cbReserved2
&& st_p
.lpReserved2
)
973 unsigned num
= *(unsigned*)st_p
.lpReserved2
;
979 /* Override the entries for fd 0,1,2 if we happened
980 * to change those std handles (this depends on the way cmd sets
981 * its new input & output handles)
983 sz
= max(sizeof(unsigned) + (sizeof(char) + sizeof(HANDLE
)) * 3, st_p
.cbReserved2
);
984 ptr
= heap_alloc(sz
);
985 flags
= (char*)(ptr
+ sizeof(unsigned));
986 handles
= (HANDLE
*)(flags
+ num
* sizeof(char));
988 memcpy(ptr
, st_p
.lpReserved2
, st_p
.cbReserved2
);
989 st
->cbReserved2
= sz
;
990 st
->lpReserved2
= ptr
;
992 #define WX_OPEN 0x01 /* see dlls/msvcrt/file.c */
993 if (num
<= 0 || (flags
[0] & WX_OPEN
))
995 handles
[0] = GetStdHandle(STD_INPUT_HANDLE
);
998 if (num
<= 1 || (flags
[1] & WX_OPEN
))
1000 handles
[1] = GetStdHandle(STD_OUTPUT_HANDLE
);
1001 flags
[1] |= WX_OPEN
;
1003 if (num
<= 2 || (flags
[2] & WX_OPEN
))
1005 handles
[2] = GetStdHandle(STD_ERROR_HANDLE
);
1006 flags
[2] |= WX_OPEN
;
1012 /******************************************************************************
1015 * Execute a command line as an external program. Must allow recursion.
1018 * Manual testing under windows shows PATHEXT plays a key part in this,
1019 * and the search algorithm and precedence appears to be as follows.
1022 * If directory supplied on command, just use that directory
1023 * If extension supplied on command, look for that explicit name first
1024 * Otherwise, search in each directory on the path
1026 * If extension supplied on command, look for that explicit name first
1027 * Then look for supplied name .* (even if extension supplied, so
1028 * 'garbage.exe' will match 'garbage.exe.cmd')
1029 * If any found, cycle through PATHEXT looking for name.exe one by one
1031 * Once a match has been found, it is launched - Code currently uses
1032 * findexecutable to achieve this which is left untouched.
1033 * If an executable has not been found, and we were launched through
1034 * a call, we need to check if the command is an internal command,
1035 * so go back through wcmd_execute.
1038 void WCMD_run_program (WCHAR
*command
, BOOL called
)
1040 WCHAR temp
[MAX_PATH
];
1041 WCHAR pathtosearch
[MAXSTRING
];
1043 WCHAR stemofsearch
[MAX_PATH
]; /* maximum allowed executable name is
1044 MAX_PATH, including null character */
1046 WCHAR pathext
[MAXSTRING
];
1048 BOOL extensionsupplied
= FALSE
;
1051 static const WCHAR envPath
[] = {'P','A','T','H','\0'};
1052 static const WCHAR delims
[] = {'/','\\',':','\0'};
1054 /* Quick way to get the filename is to extract the first argument. */
1055 WINE_TRACE("Running '%s' (%d)\n", wine_dbgstr_w(command
), called
);
1056 firstParam
= WCMD_parameter(command
, 0, NULL
, FALSE
, TRUE
);
1057 if (!firstParam
) return;
1059 /* Calculate the search path and stem to search for */
1060 if (strpbrkW (firstParam
, delims
) == NULL
) { /* No explicit path given, search path */
1061 static const WCHAR curDir
[] = {'.',';','\0'};
1062 strcpyW(pathtosearch
, curDir
);
1063 len
= GetEnvironmentVariableW(envPath
, &pathtosearch
[2], (sizeof(pathtosearch
)/sizeof(WCHAR
))-2);
1064 if ((len
== 0) || (len
>= (sizeof(pathtosearch
)/sizeof(WCHAR
)) - 2)) {
1065 static const WCHAR curDir
[] = {'.','\0'};
1066 strcpyW (pathtosearch
, curDir
);
1068 if (strchrW(firstParam
, '.') != NULL
) extensionsupplied
= TRUE
;
1069 if (strlenW(firstParam
) >= MAX_PATH
)
1071 WCMD_output_asis_stderr(WCMD_LoadMessage(WCMD_LINETOOLONG
));
1075 strcpyW(stemofsearch
, firstParam
);
1079 /* Convert eg. ..\fred to include a directory by removing file part */
1080 GetFullPathNameW(firstParam
, sizeof(pathtosearch
)/sizeof(WCHAR
), pathtosearch
, NULL
);
1081 lastSlash
= strrchrW(pathtosearch
, '\\');
1082 if (lastSlash
&& strchrW(lastSlash
, '.') != NULL
) extensionsupplied
= TRUE
;
1083 strcpyW(stemofsearch
, lastSlash
+1);
1085 /* Reduce pathtosearch to a path with trailing '\' to support c:\a.bat and
1086 c:\windows\a.bat syntax */
1087 if (lastSlash
) *(lastSlash
+ 1) = 0x00;
1090 /* Now extract PATHEXT */
1091 len
= GetEnvironmentVariableW(envPathExt
, pathext
, sizeof(pathext
)/sizeof(WCHAR
));
1092 if ((len
== 0) || (len
>= (sizeof(pathext
)/sizeof(WCHAR
)))) {
1093 strcpyW (pathext
, dfltPathExt
);
1096 /* Loop through the search path, dir by dir */
1097 pathposn
= pathtosearch
;
1098 WINE_TRACE("Searching in '%s' for '%s'\n", wine_dbgstr_w(pathtosearch
),
1099 wine_dbgstr_w(stemofsearch
));
1101 WCHAR thisDir
[MAX_PATH
] = {'\0'};
1105 /* Work on the first directory on the search path */
1106 pos
= strchrW(pathposn
, ';');
1108 memcpy(thisDir
, pathposn
, (pos
-pathposn
) * sizeof(WCHAR
));
1109 thisDir
[(pos
-pathposn
)] = 0x00;
1113 strcpyW(thisDir
, pathposn
);
1117 /* Since you can have eg. ..\.. on the path, need to expand
1118 to full information */
1119 strcpyW(temp
, thisDir
);
1120 GetFullPathNameW(temp
, MAX_PATH
, thisDir
, NULL
);
1122 /* 1. If extension supplied, see if that file exists */
1123 strcatW(thisDir
, slashW
);
1124 strcatW(thisDir
, stemofsearch
);
1125 pos
= &thisDir
[strlenW(thisDir
)]; /* Pos = end of name */
1127 /* 1. If extension supplied, see if that file exists */
1128 if (extensionsupplied
) {
1129 if (GetFileAttributesW(thisDir
) != INVALID_FILE_ATTRIBUTES
) {
1134 /* 2. Any .* matches? */
1137 WIN32_FIND_DATAW finddata
;
1138 static const WCHAR allFiles
[] = {'.','*','\0'};
1140 strcatW(thisDir
,allFiles
);
1141 h
= FindFirstFileW(thisDir
, &finddata
);
1143 if (h
!= INVALID_HANDLE_VALUE
) {
1145 WCHAR
*thisExt
= pathext
;
1147 /* 3. Yes - Try each path ext */
1149 WCHAR
*nextExt
= strchrW(thisExt
, ';');
1152 memcpy(pos
, thisExt
, (nextExt
-thisExt
) * sizeof(WCHAR
));
1153 pos
[(nextExt
-thisExt
)] = 0x00;
1154 thisExt
= nextExt
+1;
1156 strcpyW(pos
, thisExt
);
1160 if (GetFileAttributesW(thisDir
) != INVALID_FILE_ATTRIBUTES
) {
1168 /* Once found, launch it */
1171 PROCESS_INFORMATION pe
;
1175 WCHAR
*ext
= strrchrW( thisDir
, '.' );
1176 static const WCHAR batExt
[] = {'.','b','a','t','\0'};
1177 static const WCHAR cmdExt
[] = {'.','c','m','d','\0'};
1179 WINE_TRACE("Found as %s\n", wine_dbgstr_w(thisDir
));
1181 /* Special case BAT and CMD */
1182 if (ext
&& (!strcmpiW(ext
, batExt
) || !strcmpiW(ext
, cmdExt
))) {
1183 BOOL oldinteractive
= interactive
;
1184 interactive
= FALSE
;
1185 WCMD_batch (thisDir
, command
, called
, NULL
, INVALID_HANDLE_VALUE
);
1186 interactive
= oldinteractive
;
1190 /* thisDir contains the file to be launched, but with what?
1191 eg. a.exe will require a.exe to be launched, a.html may be iexplore */
1192 hinst
= FindExecutableW (thisDir
, NULL
, temp
);
1193 if ((INT_PTR
)hinst
< 32)
1196 console
= SHGetFileInfoW(temp
, 0, &psfi
, sizeof(psfi
), SHGFI_EXETYPE
);
1198 ZeroMemory (&st
, sizeof(STARTUPINFOW
));
1199 st
.cb
= sizeof(STARTUPINFOW
);
1200 init_msvcrt_io_block(&st
);
1202 /* Launch the process and if a CUI wait on it to complete
1203 Note: Launching internal wine processes cannot specify a full path to exe */
1204 status
= CreateProcessW(thisDir
,
1205 command
, NULL
, NULL
, TRUE
, 0, NULL
, NULL
, &st
, &pe
);
1206 heap_free(st
.lpReserved2
);
1207 if ((opt_c
|| opt_k
) && !opt_s
&& !status
1208 && GetLastError()==ERROR_FILE_NOT_FOUND
&& command
[0]=='\"') {
1209 /* strip first and last quote WCHARacters and try again */
1210 WCMD_strip_quotes(command
);
1212 WCMD_run_program(command
, called
);
1219 /* Always wait when non-interactive (cmd /c or in batch program),
1220 or for console applications */
1221 if (!interactive
|| (console
&& !HIWORD(console
)))
1222 WaitForSingleObject (pe
.hProcess
, INFINITE
);
1223 GetExitCodeProcess (pe
.hProcess
, &errorlevel
);
1224 if (errorlevel
== STILL_ACTIVE
) errorlevel
= 0;
1226 CloseHandle(pe
.hProcess
);
1227 CloseHandle(pe
.hThread
);
1233 /* Not found anywhere - were we called? */
1235 CMD_LIST
*toExecute
= NULL
; /* Commands left to be executed */
1237 /* Parse the command string, without reading any more input */
1238 WCMD_ReadAndParseLine(command
, &toExecute
, INVALID_HANDLE_VALUE
);
1239 WCMD_process_commands(toExecute
, FALSE
, called
);
1240 WCMD_free_commands(toExecute
);
1245 /* Not found anywhere - give up */
1246 WCMD_output_stderr(WCMD_LoadMessage(WCMD_NO_COMMAND_FOUND
), command
);
1248 /* If a command fails to launch, it sets errorlevel 9009 - which
1249 does not seem to have any associated constant definition */
1255 /*****************************************************************************
1256 * Process one command. If the command is EXIT this routine does not return.
1257 * We will recurse through here executing batch files.
1258 * Note: If call is used to a non-existing program, we reparse the line and
1259 * try to run it as an internal command. 'retrycall' represents whether
1260 * we are attempting this retry.
1262 void WCMD_execute (const WCHAR
*command
, const WCHAR
*redirects
,
1263 CMD_LIST
**cmdList
, BOOL retrycall
)
1265 WCHAR
*cmd
, *p
, *redir
;
1267 DWORD count
, creationDisposition
;
1270 SECURITY_ATTRIBUTES sa
;
1271 WCHAR
*new_cmd
= NULL
;
1272 WCHAR
*new_redir
= NULL
;
1273 HANDLE old_stdhandles
[3] = {GetStdHandle (STD_INPUT_HANDLE
),
1274 GetStdHandle (STD_OUTPUT_HANDLE
),
1275 GetStdHandle (STD_ERROR_HANDLE
)};
1276 DWORD idx_stdhandles
[3] = {STD_INPUT_HANDLE
,
1279 BOOL prev_echo_mode
, piped
= FALSE
;
1281 WINE_TRACE("command on entry:%s (%p)\n",
1282 wine_dbgstr_w(command
), cmdList
);
1284 /* If the next command is a pipe then we implement pipes by redirecting
1285 the output from this command to a temp file and input into the
1286 next command from that temp file.
1287 FIXME: Use of named pipes would make more sense here as currently this
1288 process has to finish before the next one can start but this requires
1289 a change to not wait for the first app to finish but rather the pipe */
1290 if (cmdList
&& (*cmdList
)->nextcommand
&&
1291 (*cmdList
)->nextcommand
->prevDelim
== CMD_PIPE
) {
1293 WCHAR temp_path
[MAX_PATH
];
1294 static const WCHAR cmdW
[] = {'C','M','D','\0'};
1296 /* Remember piping is in action */
1297 WINE_TRACE("Output needs to be piped\n");
1300 /* Generate a unique temporary filename */
1301 GetTempPathW(sizeof(temp_path
)/sizeof(WCHAR
), temp_path
);
1302 GetTempFileNameW(temp_path
, cmdW
, 0, (*cmdList
)->nextcommand
->pipeFile
);
1303 WINE_TRACE("Using temporary file of %s\n",
1304 wine_dbgstr_w((*cmdList
)->nextcommand
->pipeFile
));
1307 /* Move copy of the command onto the heap so it can be expanded */
1308 new_cmd
= heap_alloc(MAXSTRING
* sizeof(WCHAR
));
1309 strcpyW(new_cmd
, command
);
1311 /* Move copy of the redirects onto the heap so it can be expanded */
1312 new_redir
= heap_alloc(MAXSTRING
* sizeof(WCHAR
));
1314 /* If piped output, send stdout to the pipe by appending >filename to redirects */
1316 static const WCHAR redirOut
[] = {'%','s',' ','>',' ','%','s','\0'};
1317 wsprintfW (new_redir
, redirOut
, redirects
, (*cmdList
)->nextcommand
->pipeFile
);
1318 WINE_TRACE("Redirects now %s\n", wine_dbgstr_w(new_redir
));
1320 strcpyW(new_redir
, redirects
);
1323 /* Expand variables in command line mode only (batch mode will
1324 be expanded as the line is read in, except for 'for' loops) */
1325 handleExpansion(new_cmd
, (context
!= NULL
), delayedsubst
);
1326 handleExpansion(new_redir
, (context
!= NULL
), delayedsubst
);
1330 * Changing default drive has to be handled as a special case.
1333 if ((strlenW(cmd
) == 2) && (cmd
[1] == ':') && IsCharAlphaW(cmd
[0])) {
1335 WCHAR dir
[MAX_PATH
];
1337 /* According to MSDN CreateProcess docs, special env vars record
1338 the current directory on each drive, in the form =C:
1339 so see if one specified, and if so go back to it */
1340 strcpyW(envvar
, equalW
);
1341 strcatW(envvar
, cmd
);
1342 if (GetEnvironmentVariableW(envvar
, dir
, MAX_PATH
) == 0) {
1343 static const WCHAR fmt
[] = {'%','s','\\','\0'};
1344 wsprintfW(cmd
, fmt
, cmd
);
1345 WINE_TRACE("No special directory settings, using dir of %s\n", wine_dbgstr_w(cmd
));
1347 WINE_TRACE("Got directory %s as %s\n", wine_dbgstr_w(envvar
), wine_dbgstr_w(cmd
));
1348 status
= SetCurrentDirectoryW(cmd
);
1349 if (!status
) WCMD_print_error ();
1351 heap_free(new_redir
);
1355 sa
.nLength
= sizeof(sa
);
1356 sa
.lpSecurityDescriptor
= NULL
;
1357 sa
.bInheritHandle
= TRUE
;
1360 * Redirect stdin, stdout and/or stderr if required.
1363 /* STDIN could come from a preceding pipe, so delete on close if it does */
1364 if (cmdList
&& (*cmdList
)->pipeFile
[0] != 0x00) {
1365 WINE_TRACE("Input coming from %s\n", wine_dbgstr_w((*cmdList
)->pipeFile
));
1366 h
= CreateFileW((*cmdList
)->pipeFile
, GENERIC_READ
,
1367 FILE_SHARE_READ
| FILE_SHARE_WRITE
, &sa
, OPEN_EXISTING
,
1368 FILE_ATTRIBUTE_NORMAL
| FILE_FLAG_DELETE_ON_CLOSE
, NULL
);
1369 if (h
== INVALID_HANDLE_VALUE
) {
1370 WCMD_print_error ();
1372 heap_free(new_redir
);
1375 SetStdHandle (STD_INPUT_HANDLE
, h
);
1377 /* No need to remember the temporary name any longer once opened */
1378 (*cmdList
)->pipeFile
[0] = 0x00;
1380 /* Otherwise STDIN could come from a '<' redirect */
1381 } else if ((p
= strchrW(new_redir
,'<')) != NULL
) {
1382 h
= CreateFileW(WCMD_parameter(++p
, 0, NULL
, FALSE
, FALSE
), GENERIC_READ
, FILE_SHARE_READ
,
1383 &sa
, OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, NULL
);
1384 if (h
== INVALID_HANDLE_VALUE
) {
1385 WCMD_print_error ();
1387 heap_free(new_redir
);
1390 SetStdHandle (STD_INPUT_HANDLE
, h
);
1393 /* Scan the whole command looking for > and 2> */
1395 while (redir
!= NULL
&& ((p
= strchrW(redir
,'>')) != NULL
)) {
1398 if (p
> redir
&& (*(p
-1)=='2'))
1405 creationDisposition
= OPEN_ALWAYS
;
1409 creationDisposition
= CREATE_ALWAYS
;
1412 /* Add support for 2>&1 */
1415 int idx
= *(p
+1) - '0';
1417 if (DuplicateHandle(GetCurrentProcess(),
1418 GetStdHandle(idx_stdhandles
[idx
]),
1419 GetCurrentProcess(),
1421 0, TRUE
, DUPLICATE_SAME_ACCESS
) == 0) {
1422 WINE_FIXME("Duplicating handle failed with gle %d\n", GetLastError());
1424 WINE_TRACE("Redirect %d (%p) to %d (%p)\n", handle
, GetStdHandle(idx_stdhandles
[idx
]), idx
, h
);
1427 WCHAR
*param
= WCMD_parameter(p
, 0, NULL
, FALSE
, FALSE
);
1428 h
= CreateFileW(param
, GENERIC_WRITE
, FILE_SHARE_READ
| FILE_SHARE_DELETE
,
1429 &sa
, creationDisposition
, FILE_ATTRIBUTE_NORMAL
, NULL
);
1430 if (h
== INVALID_HANDLE_VALUE
) {
1431 WCMD_print_error ();
1433 heap_free(new_redir
);
1436 if (SetFilePointer (h
, 0, NULL
, FILE_END
) ==
1437 INVALID_SET_FILE_POINTER
) {
1438 WCMD_print_error ();
1440 WINE_TRACE("Redirect %d to '%s' (%p)\n", handle
, wine_dbgstr_w(param
), h
);
1443 SetStdHandle (idx_stdhandles
[handle
], h
);
1447 * Strip leading whitespaces, and a '@' if supplied
1449 whichcmd
= WCMD_skip_leading_spaces(cmd
);
1450 WINE_TRACE("Command: '%s'\n", wine_dbgstr_w(cmd
));
1451 if (whichcmd
[0] == '@') whichcmd
++;
1454 * Check if the command entered is internal. If it is, pass the rest of the
1455 * line down to the command. If not try to run a program.
1459 while (IsCharAlphaNumericW(whichcmd
[count
])) {
1462 for (i
=0; i
<=WCMD_EXIT
; i
++) {
1463 if (CompareStringW(LOCALE_USER_DEFAULT
, NORM_IGNORECASE
| SORT_STRINGSORT
,
1464 whichcmd
, count
, inbuilt
[i
], -1) == CSTR_EQUAL
) break;
1466 p
= WCMD_skip_leading_spaces (&whichcmd
[count
]);
1467 WCMD_parse (p
, quals
, param1
, param2
);
1468 WINE_TRACE("param1: %s, param2: %s\n", wine_dbgstr_w(param1
), wine_dbgstr_w(param2
));
1470 if (i
<= WCMD_EXIT
&& (p
[0] == '/') && (p
[1] == '?')) {
1471 /* this is a help request for a builtin program */
1473 memcpy(p
, whichcmd
, count
* sizeof(WCHAR
));
1485 WCMD_setshow_default (p
);
1488 WCMD_clear_screen ();
1497 WCMD_setshow_date ();
1507 WCMD_echo(&whichcmd
[count
]);
1510 WCMD_goto (cmdList
);
1516 WCMD_volume (TRUE
, p
);
1520 WCMD_create_dir (p
);
1526 WCMD_setshow_path (p
);
1532 WCMD_setshow_prompt ();
1542 WCMD_remove_dir (p
);
1551 WCMD_setshow_env (p
);
1560 WCMD_setshow_time ();
1563 if (strlenW(&whichcmd
[count
]) > 0)
1564 WCMD_title(&whichcmd
[count
+1]);
1570 WCMD_output_asis(newlineW
);
1577 WCMD_volume (FALSE
, p
);
1586 WCMD_assoc(p
, TRUE
);
1592 WCMD_assoc(p
, FALSE
);
1604 WCMD_exit (cmdList
);
1608 /* Very oddly, probably because of all the special parsing required for
1609 these two commands, neither 'for' nor 'if' is supported when called,
1610 i.e. 'call if 1==1...' will fail. */
1612 if (i
==WCMD_FOR
) WCMD_for (p
, cmdList
);
1613 else if (i
==WCMD_IF
) WCMD_if (p
, cmdList
);
1616 /* else: drop through */
1618 prev_echo_mode
= echo_mode
;
1619 WCMD_run_program (whichcmd
, FALSE
);
1620 echo_mode
= prev_echo_mode
;
1623 heap_free(new_redir
);
1625 /* Restore old handles */
1626 for (i
=0; i
<3; i
++) {
1627 if (old_stdhandles
[i
] != GetStdHandle(idx_stdhandles
[i
])) {
1628 CloseHandle (GetStdHandle (idx_stdhandles
[i
]));
1629 SetStdHandle (idx_stdhandles
[i
], old_stdhandles
[i
]);
1634 /*************************************************************************
1636 * Load a string from the resource file, handling any error
1637 * Returns string retrieved from resource file
1639 WCHAR
*WCMD_LoadMessage(UINT id
) {
1640 static WCHAR msg
[2048];
1641 static const WCHAR failedMsg
[] = {'F','a','i','l','e','d','!','\0'};
1643 if (!LoadStringW(GetModuleHandleW(NULL
), id
, msg
, sizeof(msg
)/sizeof(WCHAR
))) {
1644 WINE_FIXME("LoadString failed with %d\n", GetLastError());
1645 strcpyW(msg
, failedMsg
);
1650 /***************************************************************************
1653 * Dumps out the parsed command line to ensure syntax is correct
1655 static void WCMD_DumpCommands(CMD_LIST
*commands
) {
1656 CMD_LIST
*thisCmd
= commands
;
1658 WINE_TRACE("Parsed line:\n");
1659 while (thisCmd
!= NULL
) {
1660 WINE_TRACE("%p %d %2.2d %p %s Redir:%s\n",
1663 thisCmd
->bracketDepth
,
1664 thisCmd
->nextcommand
,
1665 wine_dbgstr_w(thisCmd
->command
),
1666 wine_dbgstr_w(thisCmd
->redirects
));
1667 thisCmd
= thisCmd
->nextcommand
;
1671 /***************************************************************************
1674 * Adds a command to the current command list
1676 static void WCMD_addCommand(WCHAR
*command
, int *commandLen
,
1677 WCHAR
*redirs
, int *redirLen
,
1678 WCHAR
**copyTo
, int **copyToLen
,
1679 CMD_DELIMITERS prevDelim
, int curDepth
,
1680 CMD_LIST
**lastEntry
, CMD_LIST
**output
) {
1682 CMD_LIST
*thisEntry
= NULL
;
1684 /* Allocate storage for command */
1685 thisEntry
= heap_alloc(sizeof(CMD_LIST
));
1687 /* Copy in the command */
1689 thisEntry
->command
= heap_alloc((*commandLen
+1) * sizeof(WCHAR
));
1690 memcpy(thisEntry
->command
, command
, *commandLen
* sizeof(WCHAR
));
1691 thisEntry
->command
[*commandLen
] = 0x00;
1693 /* Copy in the redirects */
1694 thisEntry
->redirects
= heap_alloc((*redirLen
+1) * sizeof(WCHAR
));
1695 memcpy(thisEntry
->redirects
, redirs
, *redirLen
* sizeof(WCHAR
));
1696 thisEntry
->redirects
[*redirLen
] = 0x00;
1697 thisEntry
->pipeFile
[0] = 0x00;
1699 /* Reset the lengths */
1702 *copyToLen
= commandLen
;
1706 thisEntry
->command
= NULL
;
1707 thisEntry
->redirects
= NULL
;
1708 thisEntry
->pipeFile
[0] = 0x00;
1711 /* Fill in other fields */
1712 thisEntry
->nextcommand
= NULL
;
1713 thisEntry
->prevDelim
= prevDelim
;
1714 thisEntry
->bracketDepth
= curDepth
;
1716 (*lastEntry
)->nextcommand
= thisEntry
;
1718 *output
= thisEntry
;
1720 *lastEntry
= thisEntry
;
1724 /***************************************************************************
1727 * Checks if the quote pointed to is the end-quote.
1731 * 1) The current parameter ends at EOL or at the beginning
1732 * of a redirection or pipe and not in a quote section.
1734 * 2) If the next character is a space and not in a quote section.
1736 * Returns TRUE if this is an end quote, and FALSE if it is not.
1739 static BOOL
WCMD_IsEndQuote(const WCHAR
*quote
, int quoteIndex
)
1741 int quoteCount
= quoteIndex
;
1744 /* If we are not in a quoted section, then we are not an end-quote */
1750 /* Check how many quotes are left for this parameter */
1751 for(i
=0;quote
[i
];i
++)
1758 /* Quote counting ends at EOL, redirection, space or pipe if current quote is complete */
1759 else if(((quoteCount
% 2) == 0)
1760 && ((quote
[i
] == '<') || (quote
[i
] == '>') || (quote
[i
] == '|') || (quote
[i
] == ' ')))
1766 /* If the quote is part of the last part of a series of quotes-on-quotes, then it must
1768 if(quoteIndex
>= (quoteCount
/ 2))
1777 /***************************************************************************
1778 * WCMD_ReadAndParseLine
1780 * Either uses supplied input or
1781 * Reads a file from the handle, and then...
1782 * Parse the text buffer, splitting into separate commands
1783 * - unquoted && strings split 2 commands but the 2nd is flagged as
1785 * - ( as the first character just ups the bracket depth
1786 * - unquoted ) when bracket depth > 0 terminates a bracket and
1787 * adds a CMD_LIST structure with null command
1788 * - Anything else gets put into the command string (including
1791 WCHAR
*WCMD_ReadAndParseLine(const WCHAR
*optionalcmd
, CMD_LIST
**output
, HANDLE readFrom
)
1795 WCHAR curString
[MAXSTRING
];
1796 int curStringLen
= 0;
1797 WCHAR curRedirs
[MAXSTRING
];
1798 int curRedirsLen
= 0;
1802 CMD_LIST
*lastEntry
= NULL
;
1803 CMD_DELIMITERS prevDelim
= CMD_NONE
;
1804 static WCHAR
*extraSpace
= NULL
; /* Deliberately never freed */
1805 static const WCHAR remCmd
[] = {'r','e','m'};
1806 static const WCHAR forCmd
[] = {'f','o','r'};
1807 static const WCHAR ifCmd
[] = {'i','f'};
1808 static const WCHAR ifElse
[] = {'e','l','s','e'};
1809 BOOL inOneLine
= FALSE
;
1814 BOOL onlyWhiteSpace
= FALSE
;
1815 BOOL lastWasWhiteSpace
= FALSE
;
1816 BOOL lastWasDo
= FALSE
;
1817 BOOL lastWasIn
= FALSE
;
1818 BOOL lastWasElse
= FALSE
;
1819 BOOL lastWasRedirect
= TRUE
;
1820 BOOL lastWasCaret
= FALSE
;
1822 /* Allocate working space for a command read from keyboard, file etc */
1824 extraSpace
= heap_alloc((MAXSTRING
+1) * sizeof(WCHAR
));
1827 WINE_ERR("Could not allocate memory for extraSpace\n");
1831 /* If initial command read in, use that, otherwise get input from handle */
1832 if (optionalcmd
!= NULL
) {
1833 strcpyW(extraSpace
, optionalcmd
);
1834 } else if (readFrom
== INVALID_HANDLE_VALUE
) {
1835 WINE_FIXME("No command nor handle supplied\n");
1837 if (!WCMD_fgets(extraSpace
, MAXSTRING
, readFrom
))
1840 curPos
= extraSpace
;
1842 /* Handle truncated input - issue warning */
1843 if (strlenW(extraSpace
) == MAXSTRING
-1) {
1844 WCMD_output_asis_stderr(WCMD_LoadMessage(WCMD_TRUNCATEDLINE
));
1845 WCMD_output_asis_stderr(extraSpace
);
1846 WCMD_output_asis_stderr(newlineW
);
1849 /* Replace env vars if in a batch context */
1850 if (context
) handleExpansion(extraSpace
, FALSE
, FALSE
);
1852 /* Skip preceding whitespace */
1853 while (*curPos
== ' ' || *curPos
== '\t') curPos
++;
1855 /* Show prompt before batch line IF echo is on and in batch program */
1856 if (context
&& echo_mode
&& *curPos
&& (*curPos
!= '@')) {
1857 static const WCHAR echoDot
[] = {'e','c','h','o','.'};
1858 static const WCHAR echoCol
[] = {'e','c','h','o',':'};
1859 static const WCHAR echoSlash
[] = {'e','c','h','o','/'};
1860 const DWORD len
= sizeof(echoDot
)/sizeof(echoDot
[0]);
1861 DWORD curr_size
= strlenW(curPos
);
1862 DWORD min_len
= (curr_size
< len
? curr_size
: len
);
1864 WCMD_output_asis(curPos
);
1865 /* I don't know why Windows puts a space here but it does */
1866 /* Except for lines starting with 'echo.', 'echo:' or 'echo/'. Ask MS why */
1867 if (CompareStringW(LOCALE_SYSTEM_DEFAULT
, NORM_IGNORECASE
,
1868 curPos
, min_len
, echoDot
, len
) != CSTR_EQUAL
1869 && CompareStringW(LOCALE_SYSTEM_DEFAULT
, NORM_IGNORECASE
,
1870 curPos
, min_len
, echoCol
, len
) != CSTR_EQUAL
1871 && CompareStringW(LOCALE_SYSTEM_DEFAULT
, NORM_IGNORECASE
,
1872 curPos
, min_len
, echoSlash
, len
) != CSTR_EQUAL
)
1874 WCMD_output_asis(spaceW
);
1876 WCMD_output_asis(newlineW
);
1879 /* Skip repeated 'no echo' characters */
1880 while (*curPos
== '@') curPos
++;
1882 /* Start with an empty string, copying to the command string */
1885 curCopyTo
= curString
;
1886 curLen
= &curStringLen
;
1887 lastWasRedirect
= FALSE
; /* Required e.g. for spaces between > and filename */
1889 /* Parse every character on the line being processed */
1890 while (*curPos
!= 0x00) {
1895 WINE_TRACE("Looking at '%c' (len:%d, lws:%d, ows:%d)\n", *curPos, *curLen,
1896 lastWasWhiteSpace, onlyWhiteSpace);
1899 /* Prevent overflow caused by the caret escape char */
1900 if (*curLen
>= MAXSTRING
) {
1901 WINE_ERR("Overflow detected in command\n");
1905 /* Certain commands need special handling */
1906 if (curStringLen
== 0 && curCopyTo
== curString
) {
1907 static const WCHAR forDO
[] = {'d','o'};
1909 /* If command starts with 'rem ' or identifies a label, ignore any &&, ( etc. */
1910 if (WCMD_keyword_ws_found(remCmd
, sizeof(remCmd
)/sizeof(remCmd
[0]), curPos
) ||
1914 } else if (WCMD_keyword_ws_found(forCmd
, sizeof(forCmd
)/sizeof(forCmd
[0]), curPos
)) {
1917 /* If command starts with 'if ' or 'else ', handle ('s mid line. We should ensure this
1918 is only true in the command portion of the IF statement, but this
1919 should suffice for now
1920 FIXME: Silly syntax like "if 1(==1( (
1922 )" will be parsed wrong */
1923 } else if (WCMD_keyword_ws_found(ifCmd
, sizeof(ifCmd
)/sizeof(ifCmd
[0]), curPos
)) {
1926 } else if (WCMD_keyword_ws_found(ifElse
, sizeof(ifElse
)/sizeof(ifElse
[0]), curPos
)) {
1927 const int keyw_len
= sizeof(ifElse
)/sizeof(ifElse
[0]) + 1;
1930 onlyWhiteSpace
= TRUE
;
1931 memcpy(&curCopyTo
[*curLen
], curPos
, keyw_len
*sizeof(WCHAR
));
1932 (*curLen
)+=keyw_len
;
1936 /* In a for loop, the DO command will follow a close bracket followed by
1937 whitespace, followed by DO, ie closeBracket inserts a NULL entry, curLen
1938 is then 0, and all whitespace is skipped */
1940 WCMD_keyword_ws_found(forDO
, sizeof(forDO
)/sizeof(forDO
[0]), curPos
)) {
1941 const int keyw_len
= sizeof(forDO
)/sizeof(forDO
[0]) + 1;
1942 WINE_TRACE("Found 'DO '\n");
1944 onlyWhiteSpace
= TRUE
;
1945 memcpy(&curCopyTo
[*curLen
], curPos
, keyw_len
*sizeof(WCHAR
));
1946 (*curLen
)+=keyw_len
;
1950 } else if (curCopyTo
== curString
) {
1952 /* Special handling for the 'FOR' command */
1953 if (inFor
&& lastWasWhiteSpace
) {
1954 static const WCHAR forIN
[] = {'i','n'};
1956 WINE_TRACE("Found 'FOR ', comparing next parm: '%s'\n", wine_dbgstr_w(curPos
));
1958 if (WCMD_keyword_ws_found(forIN
, sizeof(forIN
)/sizeof(forIN
[0]), curPos
)) {
1959 const int keyw_len
= sizeof(forIN
)/sizeof(forIN
[0]) + 1;
1960 WINE_TRACE("Found 'IN '\n");
1962 onlyWhiteSpace
= TRUE
;
1963 memcpy(&curCopyTo
[*curLen
], curPos
, keyw_len
*sizeof(WCHAR
));
1964 (*curLen
)+=keyw_len
;
1971 /* Nothing 'ends' a one line statement (e.g. REM or :labels mean
1972 the &&, quotes and redirection etc are ineffective, so just force
1973 the use of the default processing by skipping character specific
1975 if (!inOneLine
) thisChar
= *curPos
;
1976 else thisChar
= 'X'; /* Character with no special processing */
1978 lastWasWhiteSpace
= FALSE
; /* Will be reset below */
1979 lastWasCaret
= FALSE
;
1983 case '=': /* drop through - ignore token delimiters at the start of a command */
1984 case ',': /* drop through - ignore token delimiters at the start of a command */
1985 case '\t':/* drop through - ignore token delimiters at the start of a command */
1987 /* If a redirect in place, it ends here */
1988 if (!inQuotes
&& !lastWasRedirect
) {
1990 /* If finishing off a redirect, add a whitespace delimiter */
1991 if (curCopyTo
== curRedirs
) {
1992 curCopyTo
[(*curLen
)++] = ' ';
1994 curCopyTo
= curString
;
1995 curLen
= &curStringLen
;
1998 curCopyTo
[(*curLen
)++] = *curPos
;
2001 /* Remember just processed whitespace */
2002 lastWasWhiteSpace
= TRUE
;
2006 case '>': /* drop through - handle redirect chars the same */
2008 /* Make a redirect start here */
2010 curCopyTo
= curRedirs
;
2011 curLen
= &curRedirsLen
;
2012 lastWasRedirect
= TRUE
;
2015 /* See if 1>, 2> etc, in which case we have some patching up
2016 to do (provided there's a preceding whitespace, and enough
2017 chars read so far) */
2018 if (curStringLen
> 2
2019 && (*(curPos
-1)>='1') && (*(curPos
-1)<='9')
2020 && ((*(curPos
-2)==' ') || (*(curPos
-2)=='\t'))) {
2022 curString
[curStringLen
] = 0x00;
2023 curCopyTo
[(*curLen
)++] = *(curPos
-1);
2026 curCopyTo
[(*curLen
)++] = *curPos
;
2028 /* If a redirect is immediately followed by '&' (ie. 2>&1) then
2029 do not process that ampersand as an AND operator */
2030 if (thisChar
== '>' && *(curPos
+1) == '&') {
2031 curCopyTo
[(*curLen
)++] = *(curPos
+1);
2036 case '|': /* Pipe character only if not || */
2038 lastWasRedirect
= FALSE
;
2040 /* Add an entry to the command list */
2041 if (curStringLen
> 0) {
2043 /* Add the current command */
2044 WCMD_addCommand(curString
, &curStringLen
,
2045 curRedirs
, &curRedirsLen
,
2046 &curCopyTo
, &curLen
,
2047 prevDelim
, curDepth
,
2048 &lastEntry
, output
);
2052 if (*(curPos
+1) == '|') {
2053 curPos
++; /* Skip other | */
2054 prevDelim
= CMD_ONFAILURE
;
2056 prevDelim
= CMD_PIPE
;
2059 curCopyTo
[(*curLen
)++] = *curPos
;
2063 case '"': if (WCMD_IsEndQuote(curPos
, inQuotes
)) {
2066 inQuotes
++; /* Quotes within quotes are fun! */
2068 curCopyTo
[(*curLen
)++] = *curPos
;
2069 lastWasRedirect
= FALSE
;
2072 case '(': /* If a '(' is the first non whitespace in a command portion
2073 ie start of line or just after &&, then we read until an
2074 unquoted ) is found */
2075 WINE_TRACE("Found '(' conditions: curLen(%d), inQ(%d), onlyWS(%d)"
2076 ", for(%d, In:%d, Do:%d)"
2077 ", if(%d, else:%d, lwe:%d)\n",
2080 inFor
, lastWasIn
, lastWasDo
,
2081 inIf
, inElse
, lastWasElse
);
2082 lastWasRedirect
= FALSE
;
2084 /* Ignore open brackets inside the for set */
2085 if (*curLen
== 0 && !inIn
) {
2088 /* If in quotes, ignore brackets */
2089 } else if (inQuotes
) {
2090 curCopyTo
[(*curLen
)++] = *curPos
;
2092 /* In a FOR loop, an unquoted '(' may occur straight after
2094 In an IF statement just handle it regardless as we don't
2096 In an ELSE statement, only allow it straight away after
2097 the ELSE and whitespace
2100 (inElse
&& lastWasElse
&& onlyWhiteSpace
) ||
2101 (inFor
&& (lastWasIn
|| lastWasDo
) && onlyWhiteSpace
)) {
2103 /* If entering into an 'IN', set inIn */
2104 if (inFor
&& lastWasIn
&& onlyWhiteSpace
) {
2105 WINE_TRACE("Inside an IN\n");
2109 /* Add the current command */
2110 WCMD_addCommand(curString
, &curStringLen
,
2111 curRedirs
, &curRedirsLen
,
2112 &curCopyTo
, &curLen
,
2113 prevDelim
, curDepth
,
2114 &lastEntry
, output
);
2118 curCopyTo
[(*curLen
)++] = *curPos
;
2122 case '^': if (!inQuotes
) {
2123 /* If we reach the end of the input, we need to wait for more */
2124 if (*(curPos
+1) == 0x00) {
2125 lastWasCaret
= TRUE
;
2126 WINE_TRACE("Caret found at end of line\n");
2131 curCopyTo
[(*curLen
)++] = *curPos
;
2134 case '&': if (!inQuotes
) {
2135 lastWasRedirect
= FALSE
;
2137 /* Add an entry to the command list */
2138 if (curStringLen
> 0) {
2140 /* Add the current command */
2141 WCMD_addCommand(curString
, &curStringLen
,
2142 curRedirs
, &curRedirsLen
,
2143 &curCopyTo
, &curLen
,
2144 prevDelim
, curDepth
,
2145 &lastEntry
, output
);
2149 if (*(curPos
+1) == '&') {
2150 curPos
++; /* Skip other & */
2151 prevDelim
= CMD_ONSUCCESS
;
2153 prevDelim
= CMD_NONE
;
2156 curCopyTo
[(*curLen
)++] = *curPos
;
2160 case ')': if (!inQuotes
&& curDepth
> 0) {
2161 lastWasRedirect
= FALSE
;
2163 /* Add the current command if there is one */
2166 /* Add the current command */
2167 WCMD_addCommand(curString
, &curStringLen
,
2168 curRedirs
, &curRedirsLen
,
2169 &curCopyTo
, &curLen
,
2170 prevDelim
, curDepth
,
2171 &lastEntry
, output
);
2174 /* Add an empty entry to the command list */
2175 prevDelim
= CMD_NONE
;
2176 WCMD_addCommand(NULL
, &curStringLen
,
2177 curRedirs
, &curRedirsLen
,
2178 &curCopyTo
, &curLen
,
2179 prevDelim
, curDepth
,
2180 &lastEntry
, output
);
2183 /* Leave inIn if necessary */
2184 if (inIn
) inIn
= FALSE
;
2186 curCopyTo
[(*curLen
)++] = *curPos
;
2190 lastWasRedirect
= FALSE
;
2191 curCopyTo
[(*curLen
)++] = *curPos
;
2196 /* At various times we need to know if we have only skipped whitespace,
2197 so reset this variable and then it will remain true until a non
2198 whitespace is found */
2199 if ((thisChar
!= ' ') && (thisChar
!= '\t') && (thisChar
!= '\n'))
2200 onlyWhiteSpace
= FALSE
;
2202 /* Flag end of interest in FOR DO and IN parms once something has been processed */
2203 if (!lastWasWhiteSpace
) {
2204 lastWasIn
= lastWasDo
= FALSE
;
2207 /* If we have reached the end, add this command into the list
2208 Do not add command to list if escape char ^ was last */
2209 if (*curPos
== 0x00 && !lastWasCaret
&& *curLen
> 0) {
2211 /* Add an entry to the command list */
2212 WCMD_addCommand(curString
, &curStringLen
,
2213 curRedirs
, &curRedirsLen
,
2214 &curCopyTo
, &curLen
,
2215 prevDelim
, curDepth
,
2216 &lastEntry
, output
);
2219 /* If we have reached the end of the string, see if bracketing or
2220 final caret is outstanding */
2221 if (*curPos
== 0x00 && (curDepth
> 0 || lastWasCaret
) &&
2222 readFrom
!= INVALID_HANDLE_VALUE
) {
2225 WINE_TRACE("Need to read more data as outstanding brackets or carets\n");
2227 prevDelim
= CMD_NONE
;
2229 memset(extraSpace
, 0x00, (MAXSTRING
+1) * sizeof(WCHAR
));
2230 extraData
= extraSpace
;
2232 /* Read more, skipping any blank lines */
2234 WINE_TRACE("Read more input\n");
2235 if (!context
) WCMD_output_asis( WCMD_LoadMessage(WCMD_MOREPROMPT
));
2236 if (!WCMD_fgets(extraData
, MAXSTRING
, readFrom
))
2239 /* Edge case for carets - a completely blank line (i.e. was just
2240 CRLF) is oddly added as an LF but then more data is received (but
2243 if (*extraSpace
== 0x00) {
2244 WINE_TRACE("Read nothing, so appending LF char and will try again\n");
2245 *extraData
++ = '\r';
2250 } while (*extraData
== 0x00);
2251 curPos
= extraSpace
;
2252 if (context
) handleExpansion(extraSpace
, FALSE
, FALSE
);
2253 /* Continue to echo commands IF echo is on and in batch program */
2254 if (context
&& echo_mode
&& extraSpace
[0] && (extraSpace
[0] != '@')) {
2255 WCMD_output_asis(extraSpace
);
2256 WCMD_output_asis(newlineW
);
2261 /* Dump out the parsed output */
2262 WCMD_DumpCommands(*output
);
2267 /***************************************************************************
2268 * WCMD_process_commands
2270 * Process all the commands read in so far
2272 CMD_LIST
*WCMD_process_commands(CMD_LIST
*thisCmd
, BOOL oneBracket
,
2277 if (thisCmd
&& oneBracket
) bdepth
= thisCmd
->bracketDepth
;
2279 /* Loop through the commands, processing them one by one */
2282 CMD_LIST
*origCmd
= thisCmd
;
2284 /* If processing one bracket only, and we find the end bracket
2285 entry (or less), return */
2286 if (oneBracket
&& !thisCmd
->command
&&
2287 bdepth
<= thisCmd
->bracketDepth
) {
2288 WINE_TRACE("Finished bracket @ %p, next command is %p\n",
2289 thisCmd
, thisCmd
->nextcommand
);
2290 return thisCmd
->nextcommand
;
2293 /* Ignore the NULL entries a ')' inserts (Only 'if' cares
2294 about them and it will be handled in there)
2295 Also, skip over any batch labels (eg. :fred) */
2296 if (thisCmd
->command
&& thisCmd
->command
[0] != ':') {
2297 WINE_TRACE("Executing command: '%s'\n", wine_dbgstr_w(thisCmd
->command
));
2298 WCMD_execute (thisCmd
->command
, thisCmd
->redirects
, &thisCmd
, retrycall
);
2301 /* Step on unless the command itself already stepped on */
2302 if (thisCmd
== origCmd
) thisCmd
= thisCmd
->nextcommand
;
2307 /***************************************************************************
2308 * WCMD_free_commands
2310 * Frees the storage held for a parsed command line
2311 * - This is not done in the process_commands, as eventually the current
2312 * pointer will be modified within the commands, and hence a single free
2313 * routine is simpler
2315 void WCMD_free_commands(CMD_LIST
*cmds
) {
2317 /* Loop through the commands, freeing them one by one */
2319 CMD_LIST
*thisCmd
= cmds
;
2320 cmds
= cmds
->nextcommand
;
2321 heap_free(thisCmd
->command
);
2322 heap_free(thisCmd
->redirects
);
2328 /*****************************************************************************
2329 * Main entry point. This is a console application so we have a main() not a
2333 int wmain (int argc
, WCHAR
*argvW
[])
2336 WCHAR
*cmdLine
= NULL
;
2338 WCHAR
*argPos
= NULL
;
2343 static const WCHAR offW
[] = {'O','F','F','\0'};
2344 static const WCHAR promptW
[] = {'P','R','O','M','P','T','\0'};
2345 static const WCHAR defaultpromptW
[] = {'$','P','$','G','\0'};
2346 CMD_LIST
*toExecute
= NULL
; /* Commands left to be executed */
2352 /* Get the windows version being emulated */
2353 osv
.dwOSVersionInfoSize
= sizeof(osv
);
2354 GetVersionExW(&osv
);
2356 /* Pre initialize some messages */
2357 strcpyW(anykey
, WCMD_LoadMessage(WCMD_ANYKEY
));
2358 sprintf(osver
, "%d.%d.%d (%s)", osv
.dwMajorVersion
, osv
.dwMinorVersion
,
2359 osv
.dwBuildNumber
, PACKAGE_VERSION
);
2360 cmd
= WCMD_format_string(WCMD_LoadMessage(WCMD_VERSION
), osver
);
2361 strcpyW(version_string
, cmd
);
2365 /* Can't use argc/argv as it will have stripped quotes from parameters
2366 * meaning cmd.exe /C echo "quoted string" is impossible
2368 cmdLine
= GetCommandLineW();
2369 WINE_TRACE("Full commandline '%s'\n", wine_dbgstr_w(cmdLine
));
2372 opt_c
= opt_k
= opt_q
= opt_s
= FALSE
;
2373 WCMD_parameter(cmdLine
, args
, &argPos
, TRUE
, TRUE
);
2374 while (argPos
&& argPos
[0] != 0x00)
2377 WINE_TRACE("Command line parm: '%s'\n", wine_dbgstr_w(argPos
));
2378 if (argPos
[0]!='/' || argPos
[1]=='\0') {
2380 WCMD_parameter(cmdLine
, args
, &argPos
, TRUE
, TRUE
);
2385 if (tolowerW(c
)=='c') {
2387 } else if (tolowerW(c
)=='q') {
2389 } else if (tolowerW(c
)=='k') {
2391 } else if (tolowerW(c
)=='s') {
2393 } else if (tolowerW(c
)=='a') {
2394 unicodeOutput
= FALSE
;
2395 } else if (tolowerW(c
)=='u') {
2396 unicodeOutput
= TRUE
;
2397 } else if (tolowerW(c
)=='v' && argPos
[2]==':') {
2398 delayedsubst
= strncmpiW(&argPos
[3], offW
, 3);
2399 if (delayedsubst
) WINE_TRACE("Delayed substitution is on\n");
2400 } else if (tolowerW(c
)=='t' && argPos
[2]==':') {
2401 opt_t
=strtoulW(&argPos
[3], NULL
, 16);
2402 } else if (tolowerW(c
)=='x' || tolowerW(c
)=='y') {
2403 /* Ignored for compatibility with Windows */
2406 if (argPos
[2]==0 || argPos
[2]==' ' || argPos
[2]=='\t' ||
2409 WCMD_parameter(cmdLine
, args
, &argPos
, TRUE
, TRUE
);
2411 else /* handle `cmd /cnotepad.exe` and `cmd /x/c ...` */
2413 /* Do not step to next parameter, instead carry on parsing this one */
2417 if (opt_c
|| opt_k
) /* break out of parsing immediately after c or k */
2425 /* Until we start to read from the keyboard, stay as non-interactive */
2426 interactive
= FALSE
;
2428 SetEnvironmentVariableW(promptW
, defaultpromptW
);
2430 if (opt_c
|| opt_k
) {
2432 WCHAR
*q1
= NULL
,*q2
= NULL
,*p
;
2434 /* Handle very edge case error scenario, "cmd.exe /c" ie when there are no
2435 * parameters after the /C or /K by pretending there was a single space */
2436 if (argPos
== NULL
) argPos
= (WCHAR
*)spaceW
;
2439 cmd
= heap_strdupW(argPos
);
2441 /* opt_s left unflagged if the command starts with and contains exactly
2442 * one quoted string (exactly two quote characters). The quoted string
2443 * must be an executable name that has whitespace and must not have the
2444 * following characters: &<>()@^| */
2447 /* 1. Confirm there is at least one quote */
2448 q1
= strchrW(argPos
, '"');
2453 /* 2. Confirm there is a second quote */
2454 q2
= strchrW(q1
+1, '"');
2459 /* 3. Ensure there are no more quotes */
2460 if (strchrW(q2
+1, '"')) opt_s
=1;
2463 /* check first parameter for a space and invalid characters. There must not be any
2464 * invalid characters, but there must be one or more whitespace */
2469 if (*p
=='&' || *p
=='<' || *p
=='>' || *p
=='(' || *p
==')'
2470 || *p
=='@' || *p
=='^' || *p
=='|') {
2474 if (*p
==' ' || *p
=='\t')
2480 WINE_TRACE("/c command line: '%s'\n", wine_dbgstr_w(cmd
));
2482 /* Finally, we only stay in new mode IF the first parameter is quoted and
2483 is a valid executable, i.e. must exist, otherwise drop back to old mode */
2485 WCHAR
*thisArg
= WCMD_parameter(cmd
, 0, NULL
, FALSE
, TRUE
);
2486 WCHAR pathext
[MAXSTRING
];
2489 /* Now extract PATHEXT */
2490 len
= GetEnvironmentVariableW(envPathExt
, pathext
, sizeof(pathext
)/sizeof(WCHAR
));
2491 if ((len
== 0) || (len
>= (sizeof(pathext
)/sizeof(WCHAR
)))) {
2492 strcpyW (pathext
, dfltPathExt
);
2495 /* If the supplied parameter has any directory information, look there */
2496 WINE_TRACE("First parameter is '%s'\n", wine_dbgstr_w(thisArg
));
2497 if (strchrW(thisArg
, '\\') != NULL
) {
2499 GetFullPathNameW(thisArg
, sizeof(string
)/sizeof(WCHAR
), string
, NULL
);
2500 WINE_TRACE("Full path name '%s'\n", wine_dbgstr_w(string
));
2501 p
= string
+ strlenW(string
);
2503 /* Does file exist with this name? */
2504 if (GetFileAttributesW(string
) != INVALID_FILE_ATTRIBUTES
) {
2505 WINE_TRACE("Found file as '%s'\n", wine_dbgstr_w(string
));
2508 WCHAR
*thisExt
= pathext
;
2510 /* No - try with each of the PATHEXT extensions */
2511 while (!found
&& thisExt
) {
2512 WCHAR
*nextExt
= strchrW(thisExt
, ';');
2515 memcpy(p
, thisExt
, (nextExt
-thisExt
) * sizeof(WCHAR
));
2516 p
[(nextExt
-thisExt
)] = 0x00;
2517 thisExt
= nextExt
+1;
2519 strcpyW(p
, thisExt
);
2523 /* Does file exist with this extension appended? */
2524 if (GetFileAttributesW(string
) != INVALID_FILE_ATTRIBUTES
) {
2525 WINE_TRACE("Found file as '%s'\n", wine_dbgstr_w(string
));
2531 /* Otherwise we now need to look in the path to see if we can find it */
2533 /* Does file exist with this name? */
2534 if (SearchPathW(NULL
, thisArg
, NULL
, sizeof(string
)/sizeof(WCHAR
), string
, NULL
) != 0) {
2535 WINE_TRACE("Found on path as '%s'\n", wine_dbgstr_w(string
));
2538 WCHAR
*thisExt
= pathext
;
2540 /* No - try with each of the PATHEXT extensions */
2541 while (!found
&& thisExt
) {
2542 WCHAR
*nextExt
= strchrW(thisExt
, ';');
2546 nextExt
= nextExt
+1;
2551 /* Does file exist with this extension? */
2552 if (SearchPathW(NULL
, thisArg
, thisExt
, sizeof(string
)/sizeof(WCHAR
), string
, NULL
) != 0) {
2553 WINE_TRACE("Found on path as '%s' with extension '%s'\n", wine_dbgstr_w(string
),
2554 wine_dbgstr_w(thisExt
));
2562 /* If not found, drop back to old behaviour */
2564 WINE_TRACE("Binary not found, dropping back to old behaviour\n");
2570 /* strip first and last quote characters if opt_s; check for invalid
2571 * executable is done later */
2572 if (opt_s
&& *cmd
=='\"')
2573 WCMD_strip_quotes(cmd
);
2576 /* Save cwd into appropriate env var (Must be before the /c processing */
2577 GetCurrentDirectoryW(sizeof(string
)/sizeof(WCHAR
), string
);
2578 if (IsCharAlphaW(string
[0]) && string
[1] == ':') {
2579 static const WCHAR fmt
[] = {'=','%','c',':','\0'};
2580 wsprintfW(envvar
, fmt
, string
[0]);
2581 SetEnvironmentVariableW(envvar
, string
);
2582 WINE_TRACE("Set %s to %s\n", wine_dbgstr_w(envvar
), wine_dbgstr_w(string
));
2586 /* If we do a "cmd /c command", we don't want to allocate a new
2587 * console since the command returns immediately. Rather, we use
2588 * the currently allocated input and output handles. This allows
2589 * us to pipe to and read from the command interpreter.
2592 /* Parse the command string, without reading any more input */
2593 WCMD_ReadAndParseLine(cmd
, &toExecute
, INVALID_HANDLE_VALUE
);
2594 WCMD_process_commands(toExecute
, FALSE
, FALSE
);
2595 WCMD_free_commands(toExecute
);
2602 SetConsoleTitleW(WCMD_LoadMessage(WCMD_CONSTITLE
));
2604 /* Note: cmd.exe /c dir does not get a new color, /k dir does */
2606 if (!(((opt_t
& 0xF0) >> 4) == (opt_t
& 0x0F))) {
2607 defaultColor
= opt_t
& 0xFF;
2612 /* Check HKCU\Software\Microsoft\Command Processor
2613 Then HKLM\Software\Microsoft\Command Processor
2614 for defaultcolour value
2615 Note Can be supplied as DWORD or REG_SZ
2616 Note2 When supplied as REG_SZ it's in decimal!!! */
2619 DWORD value
=0, size
=4;
2620 static const WCHAR regKeyW
[] = {'S','o','f','t','w','a','r','e','\\',
2621 'M','i','c','r','o','s','o','f','t','\\',
2622 'C','o','m','m','a','n','d',' ','P','r','o','c','e','s','s','o','r','\0'};
2623 static const WCHAR dfltColorW
[] = {'D','e','f','a','u','l','t','C','o','l','o','r','\0'};
2625 if (RegOpenKeyExW(HKEY_CURRENT_USER
, regKeyW
,
2626 0, KEY_READ
, &key
) == ERROR_SUCCESS
) {
2629 /* See if DWORD or REG_SZ */
2630 if (RegQueryValueExW(key
, dfltColorW
, NULL
, &type
,
2631 NULL
, NULL
) == ERROR_SUCCESS
) {
2632 if (type
== REG_DWORD
) {
2633 size
= sizeof(DWORD
);
2634 RegQueryValueExW(key
, dfltColorW
, NULL
, NULL
,
2635 (LPBYTE
)&value
, &size
);
2636 } else if (type
== REG_SZ
) {
2637 size
= sizeof(strvalue
)/sizeof(WCHAR
);
2638 RegQueryValueExW(key
, dfltColorW
, NULL
, NULL
,
2639 (LPBYTE
)strvalue
, &size
);
2640 value
= strtoulW(strvalue
, NULL
, 10);
2646 if (value
== 0 && RegOpenKeyExW(HKEY_LOCAL_MACHINE
, regKeyW
,
2647 0, KEY_READ
, &key
) == ERROR_SUCCESS
) {
2650 /* See if DWORD or REG_SZ */
2651 if (RegQueryValueExW(key
, dfltColorW
, NULL
, &type
,
2652 NULL
, NULL
) == ERROR_SUCCESS
) {
2653 if (type
== REG_DWORD
) {
2654 size
= sizeof(DWORD
);
2655 RegQueryValueExW(key
, dfltColorW
, NULL
, NULL
,
2656 (LPBYTE
)&value
, &size
);
2657 } else if (type
== REG_SZ
) {
2658 size
= sizeof(strvalue
)/sizeof(WCHAR
);
2659 RegQueryValueExW(key
, dfltColorW
, NULL
, NULL
,
2660 (LPBYTE
)strvalue
, &size
);
2661 value
= strtoulW(strvalue
, NULL
, 10);
2667 /* If one found, set the screen to that colour */
2668 if (!(((value
& 0xF0) >> 4) == (value
& 0x0F))) {
2669 defaultColor
= value
& 0xFF;
2677 /* Parse the command string, without reading any more input */
2678 WCMD_ReadAndParseLine(cmd
, &toExecute
, INVALID_HANDLE_VALUE
);
2679 WCMD_process_commands(toExecute
, FALSE
, FALSE
);
2680 WCMD_free_commands(toExecute
);
2686 * Loop forever getting commands and executing them.
2690 if (!opt_k
) WCMD_version ();
2693 /* Read until EOF (which for std input is never, but if redirect
2694 in place, may occur */
2695 if (echo_mode
) WCMD_show_prompt();
2696 if (!WCMD_ReadAndParseLine(NULL
, &toExecute
, GetStdHandle(STD_INPUT_HANDLE
)))
2698 WCMD_process_commands(toExecute
, FALSE
, FALSE
);
2699 WCMD_free_commands(toExecute
);