2 * CMD - Wine-compatible command line interface - batch interface.
4 * Copyright (C) 1999 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
23 #include "wine/debug.h"
25 extern struct env_stack
*saved_environment
;
27 WINE_DEFAULT_DEBUG_CHANNEL(cmd
);
29 /****************************************************************************
32 * Open and execute a batch file.
33 * On entry *command includes the complete command line beginning with the name
34 * of the batch file (if a CALL command was entered the CALL has been removed).
35 * *file is the name of the file, which might not exist and may not have the
36 * .BAT suffix on. Called is 1 for a CALL, 0 otherwise.
38 * We need to handle recursion correctly, since one batch program might call another.
39 * So parameters for this batch file are held in a BATCH_CONTEXT structure.
41 * To support call within the same batch program, another input parameter is
42 * a label to goto once opened.
45 void WCMD_batch (WCHAR
*file
, WCHAR
*command
, BOOL called
, WCHAR
*startLabel
, HANDLE pgmHandle
)
47 HANDLE h
= INVALID_HANDLE_VALUE
;
48 BATCH_CONTEXT
*prev_context
;
50 if (startLabel
== NULL
) {
51 h
= CreateFileW (file
, GENERIC_READ
, FILE_SHARE_READ
|FILE_SHARE_WRITE
|FILE_SHARE_DELETE
,
52 NULL
, OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, NULL
);
53 if (h
== INVALID_HANDLE_VALUE
) {
54 SetLastError (ERROR_FILE_NOT_FOUND
);
59 DuplicateHandle(GetCurrentProcess(), pgmHandle
,
60 GetCurrentProcess(), &h
,
61 0, FALSE
, DUPLICATE_SAME_ACCESS
);
65 * Create a context structure for this batch file.
68 prev_context
= context
;
69 context
= LocalAlloc (LMEM_FIXED
, sizeof (BATCH_CONTEXT
));
71 context
->batchfileW
= heap_strdupW(file
);
72 context
-> command
= command
;
73 memset(context
-> shift_count
, 0x00, sizeof(context
-> shift_count
));
74 context
-> prev_context
= prev_context
;
75 context
-> skip_rest
= FALSE
;
77 /* If processing a call :label, 'goto' the label in question */
79 strcpyW(param1
, startLabel
);
84 * Work through the file line by line. Specific batch commands are processed here,
85 * the rest are handled by the main command processor.
88 while (context
-> skip_rest
== FALSE
) {
89 CMD_LIST
*toExecute
= NULL
; /* Commands left to be executed */
90 if (!WCMD_ReadAndParseLine(NULL
, &toExecute
, h
))
92 /* Note: although this batch program itself may be called, we are not retrying
93 the command as a result of a call failing to find a program, hence the
94 retryCall parameter below is FALSE */
95 WCMD_process_commands(toExecute
, FALSE
, FALSE
);
96 WCMD_free_commands(toExecute
);
102 * If there are outstanding setlocal's to the current context, unwind them.
104 while (saved_environment
&& saved_environment
->batchhandle
== context
->h
) {
109 * If invoked by a CALL, we return to the context of our caller. Otherwise return
110 * to the caller's caller.
113 heap_free(context
->batchfileW
);
115 if ((prev_context
!= NULL
) && (!called
)) {
116 WINE_TRACE("Batch completed, but was not 'called' so skipping outer batch too\n");
117 prev_context
-> skip_rest
= TRUE
;
118 context
= prev_context
;
120 context
= prev_context
;
123 /*******************************************************************
124 * WCMD_parameter_with_delims
126 * Extracts a delimited parameter from an input string, providing
127 * the delimiters characters to use
130 * s [I] input string, non NULL
131 * n [I] # of the parameter to return, counted from 0
132 * start [O] Optional. Pointer to the first char of param n in s
133 * raw [I] TRUE to return the parameter in raw format (quotes maintained)
134 * FALSE to return the parameter with quotes stripped (including internal ones)
135 * wholecmdline [I] TRUE to indicate this routine is being used to parse the
136 * command line, and special logic for arg0->1 transition
137 * needs to be applied.
138 * delims[I] The delimiter characters to use
141 * Success: The nth delimited parameter found in s
142 * if start != NULL, *start points to the start of the param (quotes maintained)
143 * Failure: An empty string if the param is not found.
147 * Return value is stored in static storage (i.e. overwritten after each call).
148 * By default, the parameter is returned with quotes removed, ready for use with
149 * other API calls, e.g. c:\"a b"\c is returned as c:\a b\c. However, some commands
150 * need to preserve the exact syntax (echo, for, etc) hence the raw option.
152 WCHAR
*WCMD_parameter_with_delims (WCHAR
*s
, int n
, WCHAR
**start
,
153 BOOL raw
, BOOL wholecmdline
, const WCHAR
*delims
)
156 static WCHAR param
[MAXSTRING
];
157 WCHAR
*p
= s
, *begin
;
159 if (start
!= NULL
) *start
= NULL
;
164 /* Absorb repeated word delimiters until we get to the next token (or the end!) */
165 while (*p
&& (strchrW(delims
, *p
) != NULL
))
167 if (*p
== '\0') return param
;
169 /* If we have reached the token number we want, remember the beginning of it */
170 if (start
!= NULL
&& curParamNb
== n
) *start
= p
;
172 /* Return the whole word up to the next delimiter, handling quotes in the middle
173 of it, e.g. a"\b c\"d is a single parameter. */
176 /* Loop character by character, but just need to special case quotes */
178 /* Once we have found a delimiter, break */
179 if (strchrW(delims
, *p
) != NULL
) break;
181 /* Very odd special case - Seems as if a ( acts as a delimiter which is
182 not swallowed but is effective only when it comes between the program
183 name and the parameters. Need to avoid this triggering when used
184 to walk parameters generally. */
185 if (wholecmdline
&& curParamNb
== 0 && *p
=='(') break;
187 /* If we find a quote, copy until we get the end quote */
190 while (*p
&& *p
!= '"') p
++;
193 /* Now skip the character / quote */
197 if (curParamNb
== n
) {
198 /* Return the parameter in static storage either as-is (raw) or
199 suitable for use with other win32 api calls (quotes stripped) */
201 memcpy(param
, begin
, (p
- begin
) * sizeof(WCHAR
));
202 param
[p
-begin
] = '\0';
206 if (*begin
!= '"') param
[i
++] = *begin
;
217 /*******************************************************************
220 * Extracts a delimited parameter from an input string, using a
221 * default set of delimiter characters. For parameters, see the main
224 WCHAR
*WCMD_parameter (WCHAR
*s
, int n
, WCHAR
**start
, BOOL raw
,
227 static const WCHAR defaultDelims
[] = { ' ', '\t', ',', '=', ';', '\0' };
228 return WCMD_parameter_with_delims (s
, n
, start
, raw
, wholecmdline
, defaultDelims
);
231 /****************************************************************************
234 * Gets one line from a file/console and puts it into buffer buf
235 * Pre: buf has size noChars
236 * 1 <= noChars <= MAXSTRING
237 * Post: buf is filled with at most noChars-1 characters, and gets nul-terminated
238 buf does not include EOL terminator
241 * NULL on error or EOF
244 WCHAR
*WCMD_fgets(WCHAR
*buf
, DWORD noChars
, HANDLE h
)
250 /* We can't use the native f* functions because of the filename syntax differences
251 between DOS and Unix. Also need to lose the LF (or CRLF) from the line. */
253 if (!WCMD_is_console_handle(h
)) {
254 LARGE_INTEGER filepos
;
260 bufA
= heap_alloc(noChars
);
262 /* Save current file position */
263 filepos
.QuadPart
= 0;
264 SetFilePointerEx(h
, filepos
, &filepos
, FILE_CURRENT
);
266 status
= ReadFile(h
, bufA
, noChars
, &charsRead
, NULL
);
267 if (!status
|| charsRead
== 0) {
273 for (p
= bufA
; p
< (bufA
+ charsRead
); p
= CharNextExA(cp
, p
, 0)) {
274 if (*p
== '\n' || *p
== '\r')
278 /* Sets file pointer to the start of the next line, if any */
279 filepos
.QuadPart
+= p
- bufA
+ 1 + (*p
== '\r' ? 1 : 0);
280 SetFilePointerEx(h
, filepos
, NULL
, FILE_BEGIN
);
282 i
= MultiByteToWideChar(cp
, 0, bufA
, p
- bufA
, buf
, noChars
);
286 status
= WCMD_ReadFile(h
, buf
, noChars
, &charsRead
);
287 if (!status
|| charsRead
== 0) return NULL
;
290 for (i
= 0; i
< charsRead
; i
++) {
291 if (buf
[i
] == '\n' || buf
[i
] == '\r')
296 /* Truncate at EOL (or end of buffer) */
305 /* WCMD_splitpath - copied from winefile as no obvious way to use it otherwise */
306 void WCMD_splitpath(const WCHAR
* path
, WCHAR
* drv
, WCHAR
* dir
, WCHAR
* name
, WCHAR
* ext
)
308 const WCHAR
* end
; /* end of processed string */
309 const WCHAR
* p
; /* search pointer */
310 const WCHAR
* s
; /* copy pointer */
312 /* extract drive name */
313 if (path
[0] && path
[1]==':') {
322 end
= path
+ strlenW(path
);
324 /* search for begin of file extension */
325 for(p
=end
; p
>path
&& *--p
!='\\' && *p
!='/'; )
332 for(s
=end
; (*ext
=*s
++); )
335 /* search for end of directory name */
337 if (*--p
=='\\' || *p
=='/') {
357 /****************************************************************************
358 * WCMD_HandleTildaModifiers
360 * Handle the ~ modifiers when expanding %0-9 or (%a-z/A-Z in for command)
361 * %~xxxxxV (V=0-9 or A-Z, a-z)
362 * Where xxxx is any combination of:
364 * f - Fully qualified path (assumes current dir if not drive\dir)
369 * s - path with shortnames
373 * $ENVVAR: - Searches ENVVAR for (contents of V) and expands to fully
376 * To work out the length of the modifier:
378 * Note: In the case of %0-9 knowing the end of the modifier is easy,
379 * but in a for loop, the for end WCHARacter may also be a modifier
380 * eg. for %a in (c:\a.a) do echo XXX
381 * where XXX = %~a (just ~)
382 * %~aa (~ and attributes)
383 * %~aaxa (~, attributes and extension)
384 * BUT %~aax (~ and attributes followed by 'x')
386 * Hence search forwards until find an invalid modifier, and then
387 * backwards until find for variable or 0-9
389 void WCMD_HandleTildaModifiers(WCHAR
**start
, BOOL atExecute
)
392 #define NUMMODIFIERS 11
393 static const WCHAR validmodifiers
[NUMMODIFIERS
] = {
394 '~', 'f', 'd', 'p', 'n', 'x', 's', 'a', 't', 'z', '$'
397 WIN32_FILE_ATTRIBUTE_DATA fileInfo
;
398 WCHAR outputparam
[MAX_PATH
];
399 WCHAR finaloutput
[MAX_PATH
];
400 WCHAR fullfilename
[MAX_PATH
];
401 WCHAR thisoutput
[MAX_PATH
];
402 WCHAR
*pos
= *start
+1;
403 WCHAR
*firstModifier
= pos
;
404 WCHAR
*lastModifier
= NULL
;
406 BOOL finished
= FALSE
;
409 BOOL skipFileParsing
= FALSE
;
410 BOOL doneModifier
= FALSE
;
412 /* Search forwards until find invalid character modifier */
415 /* Work on the previous character */
416 if (lastModifier
!= NULL
) {
418 for (i
=0; i
<NUMMODIFIERS
; i
++) {
419 if (validmodifiers
[i
] == *lastModifier
) {
421 /* Special case '$' to skip until : found */
422 if (*lastModifier
== '$') {
423 while (*pos
!= ':' && *pos
) pos
++;
424 if (*pos
== 0x00) return; /* Invalid syntax */
425 pos
++; /* Skip ':' */
431 if (i
==NUMMODIFIERS
) {
436 /* Save this one away */
443 while (lastModifier
> firstModifier
) {
444 WINE_TRACE("Looking backwards for parameter id: %s\n",
445 wine_dbgstr_w(lastModifier
));
447 if (!atExecute
&& context
&& (*lastModifier
>= '0' && *lastModifier
<= '9')) {
448 /* Its a valid parameter identifier - OK */
452 int foridx
= FOR_VAR_IDX(*lastModifier
);
453 /* Its a valid parameter identifier - OK */
454 if ((foridx
>= 0) && (forloopcontext
.variable
[foridx
] != NULL
)) break;
456 /* Its not a valid parameter identifier - step backwards */
460 if (lastModifier
== firstModifier
) return; /* Invalid syntax */
462 /* Extract the parameter to play with */
463 if (*lastModifier
== '0') {
464 strcpyW(outputparam
, context
->batchfileW
);
465 } else if ((*lastModifier
>= '1' && *lastModifier
<= '9')) {
467 WCMD_parameter (context
-> command
,
468 *lastModifier
-'0' + context
-> shift_count
[*lastModifier
-'0'],
471 int foridx
= FOR_VAR_IDX(*lastModifier
);
472 strcpyW(outputparam
, forloopcontext
.variable
[foridx
]);
475 /* So now, firstModifier points to beginning of modifiers, lastModifier
476 points to the variable just after the modifiers. Process modifiers
477 in a specific order, remembering there could be duplicates */
478 modifierLen
= lastModifier
- firstModifier
;
479 finaloutput
[0] = 0x00;
481 /* 1. Handle '~' : Strip surrounding quotes */
482 if (outputparam
[0]=='"' &&
483 memchrW(firstModifier
, '~', modifierLen
) != NULL
) {
484 int len
= strlenW(outputparam
);
485 if (outputparam
[len
-1] == '"') {
486 outputparam
[len
-1]=0x00;
489 memmove(outputparam
, &outputparam
[1], (len
* sizeof(WCHAR
))-1);
492 /* 2. Handle the special case of a $ */
493 if (memchrW(firstModifier
, '$', modifierLen
) != NULL
) {
494 /* Special Case: Search envar specified in $[envvar] for outputparam
495 Note both $ and : are guaranteed otherwise check above would fail */
496 WCHAR
*begin
= strchrW(firstModifier
, '$') + 1;
497 WCHAR
*end
= strchrW(firstModifier
, ':');
501 /* Extract the env var */
502 memcpy(env
, begin
, (end
-begin
) * sizeof(WCHAR
));
503 env
[(end
-begin
)] = 0x00;
505 size
= GetEnvironmentVariableW(env
, NULL
, 0);
507 WCHAR
*fullpath
= heap_alloc(size
* sizeof(WCHAR
));
508 if (!fullpath
|| (GetEnvironmentVariableW(env
, fullpath
, size
) == 0) ||
509 (SearchPathW(fullpath
, outputparam
, NULL
, MAX_PATH
, outputparam
, NULL
) == 0))
515 /* If env var not found, return empty string */
516 finaloutput
[0] = 0x00;
517 outputparam
[0] = 0x00;
518 skipFileParsing
= TRUE
;
522 /* After this, we need full information on the file,
523 which is valid not to exist. */
524 if (!skipFileParsing
) {
525 if (GetFullPathNameW(outputparam
, MAX_PATH
, fullfilename
, NULL
) == 0) {
527 fullfilename
[0] = 0x00;
529 exists
= GetFileAttributesExW(fullfilename
, GetFileExInfoStandard
,
533 /* 2. Handle 'a' : Output attributes (File doesn't have to exist) */
534 if (memchrW(firstModifier
, 'a', modifierLen
) != NULL
) {
536 WCHAR defaults
[] = {'-','-','-','-','-','-','-','-','-','\0'};
540 strcpyW(thisoutput
, defaults
);
541 if (fileInfo
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
543 if (fileInfo
.dwFileAttributes
& FILE_ATTRIBUTE_READONLY
)
545 if (fileInfo
.dwFileAttributes
& FILE_ATTRIBUTE_ARCHIVE
)
547 if (fileInfo
.dwFileAttributes
& FILE_ATTRIBUTE_HIDDEN
)
549 if (fileInfo
.dwFileAttributes
& FILE_ATTRIBUTE_SYSTEM
)
551 if (fileInfo
.dwFileAttributes
& FILE_ATTRIBUTE_COMPRESSED
)
553 /* FIXME: What are 6 and 7? */
554 if (fileInfo
.dwFileAttributes
& FILE_ATTRIBUTE_REPARSE_POINT
)
556 strcatW(finaloutput
, thisoutput
);
560 /* 3. Handle 't' : Date+time (File doesn't have to exist) */
561 if (memchrW(firstModifier
, 't', modifierLen
) != NULL
) {
569 if (finaloutput
[0] != 0x00) strcatW(finaloutput
, spaceW
);
571 /* Format the time */
572 FileTimeToSystemTime(&fileInfo
.ftLastWriteTime
, &systime
);
573 GetDateFormatW(LOCALE_USER_DEFAULT
, DATE_SHORTDATE
, &systime
,
574 NULL
, thisoutput
, MAX_PATH
);
575 strcatW(thisoutput
, spaceW
);
576 datelen
= strlenW(thisoutput
);
577 GetTimeFormatW(LOCALE_USER_DEFAULT
, TIME_NOSECONDS
, &systime
,
578 NULL
, (thisoutput
+datelen
), MAX_PATH
-datelen
);
579 strcatW(finaloutput
, thisoutput
);
583 /* 4. Handle 'z' : File length (File doesn't have to exist) */
584 if (memchrW(firstModifier
, 'z', modifierLen
) != NULL
) {
585 /* FIXME: Output full 64 bit size (sprintf does not support I64 here) */
586 ULONG
/*64*/ fullsize
= /*(fileInfo.nFileSizeHigh << 32) +*/
587 fileInfo
.nFileSizeLow
;
588 static const WCHAR fmt
[] = {'%','u','\0'};
592 if (finaloutput
[0] != 0x00) strcatW(finaloutput
, spaceW
);
593 wsprintfW(thisoutput
, fmt
, fullsize
);
594 strcatW(finaloutput
, thisoutput
);
598 /* 4. Handle 's' : Use short paths (File doesn't have to exist) */
599 if (memchrW(firstModifier
, 's', modifierLen
) != NULL
) {
600 if (finaloutput
[0] != 0x00) strcatW(finaloutput
, spaceW
);
601 /* Don't flag as doneModifier - %~s on its own is processed later */
602 GetShortPathNameW(outputparam
, outputparam
, sizeof(outputparam
)/sizeof(outputparam
[0]));
605 /* 5. Handle 'f' : Fully qualified path (File doesn't have to exist) */
606 /* Note this overrides d,p,n,x */
607 if (memchrW(firstModifier
, 'f', modifierLen
) != NULL
) {
609 if (finaloutput
[0] != 0x00) strcatW(finaloutput
, spaceW
);
610 strcatW(finaloutput
, fullfilename
);
615 WCHAR fname
[MAX_PATH
];
617 BOOL doneFileModifier
= FALSE
;
618 BOOL addSpace
= (finaloutput
[0] != 0x00);
620 /* Split into components */
621 WCMD_splitpath(fullfilename
, drive
, dir
, fname
, ext
);
623 /* 5. Handle 'd' : Drive Letter */
624 if (memchrW(firstModifier
, 'd', modifierLen
) != NULL
) {
626 strcatW(finaloutput
, spaceW
);
630 strcatW(finaloutput
, drive
);
632 doneFileModifier
= TRUE
;
635 /* 6. Handle 'p' : Path */
636 if (memchrW(firstModifier
, 'p', modifierLen
) != NULL
) {
638 strcatW(finaloutput
, spaceW
);
642 strcatW(finaloutput
, dir
);
644 doneFileModifier
= TRUE
;
647 /* 7. Handle 'n' : Name */
648 if (memchrW(firstModifier
, 'n', modifierLen
) != NULL
) {
650 strcatW(finaloutput
, spaceW
);
654 strcatW(finaloutput
, fname
);
656 doneFileModifier
= TRUE
;
659 /* 8. Handle 'x' : Ext */
660 if (memchrW(firstModifier
, 'x', modifierLen
) != NULL
) {
662 strcatW(finaloutput
, spaceW
);
666 strcatW(finaloutput
, ext
);
668 doneFileModifier
= TRUE
;
671 /* If 's' but no other parameter, dump the whole thing */
672 if (!doneFileModifier
&&
673 memchrW(firstModifier
, 's', modifierLen
) != NULL
) {
675 if (finaloutput
[0] != 0x00) strcatW(finaloutput
, spaceW
);
676 strcatW(finaloutput
, outputparam
);
681 /* If No other modifier processed, just add in parameter */
682 if (!doneModifier
) strcpyW(finaloutput
, outputparam
);
684 /* Finish by inserting the replacement into the string */
685 WCMD_strsubstW(*start
, lastModifier
+1, finaloutput
, -1);
688 /*******************************************************************
689 * WCMD_call - processes a batch call statement
691 * If there is a leading ':', calls within this batch program
692 * otherwise launches another program.
694 void WCMD_call (WCHAR
*command
) {
696 /* Run other program if no leading ':' */
697 if (*command
!= ':') {
698 WCMD_run_program(command
, TRUE
);
699 /* If the thing we try to run does not exist, call returns 1 */
700 if (errorlevel
) errorlevel
=1;
703 WCHAR gotoLabel
[MAX_PATH
];
705 strcpyW(gotoLabel
, param1
);
710 FOR_CONTEXT oldcontext
;
712 /* Save the for variable context, then start with an empty context
713 as for loop variables do not survive a call */
714 oldcontext
= forloopcontext
;
715 memset(&forloopcontext
, 0, sizeof(forloopcontext
));
717 /* Save the current file position, call the same file,
720 li
.u
.LowPart
= SetFilePointer(context
-> h
, li
.u
.LowPart
,
721 &li
.u
.HighPart
, FILE_CURRENT
);
722 WCMD_batch (param1
, command
, TRUE
, gotoLabel
, context
->h
);
723 SetFilePointer(context
-> h
, li
.u
.LowPart
,
724 &li
.u
.HighPart
, FILE_BEGIN
);
726 /* Restore the for loop context */
727 forloopcontext
= oldcontext
;
729 WCMD_output_asis_stderr(WCMD_LoadMessage(WCMD_CALLINSCRIPT
));