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 WINE_DEFAULT_DEBUG_CHANNEL(cmd);
28 extern WCHAR quals[MAX_PATH], param1[MAX_PATH], param2[MAX_PATH];
29 extern BATCH_CONTEXT *context;
30 extern DWORD errorlevel;
32 /****************************************************************************
35 * Open and execute a batch file.
36 * On entry *command includes the complete command line beginning with the name
37 * of the batch file (if a CALL command was entered the CALL has been removed).
38 * *file is the name of the file, which might not exist and may not have the
39 * .BAT suffix on. Called is 1 for a CALL, 0 otherwise.
41 * We need to handle recursion correctly, since one batch program might call another.
42 * So parameters for this batch file are held in a BATCH_CONTEXT structure.
44 * To support call within the same batch program, another input parameter is
45 * a label to goto once opened.
48 void WCMD_batch (WCHAR *file, WCHAR *command, int called, WCHAR *startLabel, HANDLE pgmHandle) {
50 HANDLE h = INVALID_HANDLE_VALUE;
51 BATCH_CONTEXT *prev_context;
53 if (startLabel == NULL) {
54 h = CreateFileW (file, GENERIC_READ, FILE_SHARE_READ,
55 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
56 if (h == INVALID_HANDLE_VALUE) {
57 SetLastError (ERROR_FILE_NOT_FOUND);
62 DuplicateHandle(GetCurrentProcess(), pgmHandle,
63 GetCurrentProcess(), &h,
64 0, FALSE, DUPLICATE_SAME_ACCESS);
68 * Create a context structure for this batch file.
71 prev_context = context;
72 context = LocalAlloc (LMEM_FIXED, sizeof (BATCH_CONTEXT));
74 context->batchfileW = WCMD_strdupW(file);
75 context -> command = command;
76 memset(context -> shift_count, 0x00, sizeof(context -> shift_count));
77 context -> prev_context = prev_context;
78 context -> skip_rest = FALSE;
80 /* If processing a call :label, 'goto' the label in question */
82 strcpyW(param1, startLabel);
87 * Work through the file line by line. Specific batch commands are processed here,
88 * the rest are handled by the main command processor.
91 while (context -> skip_rest == FALSE) {
92 CMD_LIST *toExecute = NULL; /* Commands left to be executed */
93 if (WCMD_ReadAndParseLine(NULL, &toExecute, h) == NULL)
95 WCMD_process_commands(toExecute, FALSE, NULL, NULL);
96 WCMD_free_commands(toExecute);
102 * If invoked by a CALL, we return to the context of our caller. Otherwise return
103 * to the caller's caller.
106 HeapFree(GetProcessHeap(), 0, context->batchfileW);
108 if ((prev_context != NULL) && (!called)) {
109 prev_context -> skip_rest = TRUE;
110 context = prev_context;
112 context = prev_context;
115 /*******************************************************************
118 * Extracts a delimited parameter from an input string
121 * s [I] input string, non NULL
122 * n [I] # of the (possibly double quotes-delimited) parameter to return
124 * where [O] if non NULL, pointer to the start of the nth parameter in s,
125 * potentially a " character
126 * end [O] if non NULL, pointer to the last char of
127 * the nth parameter in s, potentially a " character
130 * Success: Returns the nth delimited parameter found in s.
131 * *where points to the start of the param, possibly a starting
132 * double quotes character
133 * Failure: Returns an empty string if the param is not found.
134 * *where is set to NULL
137 * Return value is stored in static storage, hence is overwritten
139 * Doesn't include any potentially delimiting double quotes
141 WCHAR *WCMD_parameter (WCHAR *s, int n, WCHAR **where, WCHAR **end) {
143 static WCHAR param[MAX_PATH];
145 BOOL quotesDelimited;
147 if (where != NULL) *where = NULL;
148 if (end != NULL) *end = NULL;
151 while (*p && ((*p == ' ') || (*p == ',') || (*p == '=') || (*p == '\t')))
153 if (*p == '\0') return param;
155 quotesDelimited = (*p == '"');
156 if (where != NULL && curParamNb == n) *where = p;
158 if (quotesDelimited) {
160 while (*p && *p != '"') p++;
163 while (*p && (*p != ' ') && (*p != ',') && (*p != '=') && (*p != '\t'))
166 if (curParamNb == n) {
167 memcpy(param, q, (p - q) * sizeof(WCHAR));
169 if (end) *end = p - 1 + quotesDelimited;
172 if (quotesDelimited && *p == '"') p++;
177 /****************************************************************************
180 * Get one line from a batch file. We can't use the native f* functions because
181 * of the filename syntax differences between DOS and Unix. Also need to lose
182 * the LF (or CRLF) from the line.
185 WCHAR *WCMD_fgets (WCHAR *s, int noChars, HANDLE h) {
193 status = WCMD_ReadFile (h, s, 1, &bytes, NULL);
194 if ((status == 0) || ((bytes == 0) && (s == p))) return NULL;
195 if (*s == '\n') bytes = 0;
196 else if (*s != '\r') {
201 } while ((bytes == 1) && (noChars > 1));
205 /* WCMD_splitpath - copied from winefile as no obvious way to use it otherwise */
206 void WCMD_splitpath(const WCHAR* path, WCHAR* drv, WCHAR* dir, WCHAR* name, WCHAR* ext)
208 const WCHAR* end; /* end of processed string */
209 const WCHAR* p; /* search pointer */
210 const WCHAR* s; /* copy pointer */
212 /* extract drive name */
213 if (path[0] && path[1]==':') {
222 end = path + strlenW(path);
224 /* search for begin of file extension */
225 for(p=end; p>path && *--p!='\\' && *p!='/'; )
232 for(s=end; (*ext=*s++); )
235 /* search for end of directory name */
237 if (*--p=='\\' || *p=='/') {
257 /****************************************************************************
258 * WCMD_HandleTildaModifiers
260 * Handle the ~ modifiers when expanding %0-9 or (%a-z in for command)
261 * %~xxxxxV (V=0-9 or A-Z)
262 * Where xxxx is any combination of:
264 * f - Fully qualified path (assumes current dir if not drive\dir)
269 * s - path with shortnames
273 * $ENVVAR: - Searches ENVVAR for (contents of V) and expands to fully
276 * To work out the length of the modifier:
278 * Note: In the case of %0-9 knowing the end of the modifier is easy,
279 * but in a for loop, the for end WCHARacter may also be a modifier
280 * eg. for %a in (c:\a.a) do echo XXX
281 * where XXX = %~a (just ~)
282 * %~aa (~ and attributes)
283 * %~aaxa (~, attributes and extension)
284 * BUT %~aax (~ and attributes followed by 'x')
286 * Hence search forwards until find an invalid modifier, and then
287 * backwards until find for variable or 0-9
289 void WCMD_HandleTildaModifiers(WCHAR **start, const WCHAR *forVariable,
290 const WCHAR *forValue, BOOL justFors) {
292 #define NUMMODIFIERS 11
293 static const WCHAR validmodifiers[NUMMODIFIERS] = {
294 '~', 'f', 'd', 'p', 'n', 'x', 's', 'a', 't', 'z', '$'
296 static const WCHAR space[] = {' ', '\0'};
298 WIN32_FILE_ATTRIBUTE_DATA fileInfo;
299 WCHAR outputparam[MAX_PATH];
300 WCHAR finaloutput[MAX_PATH];
301 WCHAR fullfilename[MAX_PATH];
302 WCHAR thisoutput[MAX_PATH];
303 WCHAR *pos = *start+1;
304 WCHAR *firstModifier = pos;
305 WCHAR *lastModifier = NULL;
307 BOOL finished = FALSE;
310 BOOL skipFileParsing = FALSE;
311 BOOL doneModifier = FALSE;
313 /* Search forwards until find invalid character modifier */
316 /* Work on the previous character */
317 if (lastModifier != NULL) {
319 for (i=0; i<NUMMODIFIERS; i++) {
320 if (validmodifiers[i] == *lastModifier) {
322 /* Special case '$' to skip until : found */
323 if (*lastModifier == '$') {
324 while (*pos != ':' && *pos) pos++;
325 if (*pos == 0x00) return; /* Invalid syntax */
326 pos++; /* Skip ':' */
332 if (i==NUMMODIFIERS) {
337 /* Save this one away */
344 while (lastModifier > firstModifier) {
345 WINE_TRACE("Looking backwards for parameter id: %s / %s\n",
346 wine_dbgstr_w(lastModifier), wine_dbgstr_w(forVariable));
348 if (!justFors && context && (*lastModifier >= '0' && *lastModifier <= '9')) {
349 /* Its a valid parameter identifier - OK */
352 } else if (forVariable && *lastModifier == *(forVariable+1)) {
353 /* Its a valid parameter identifier - OK */
360 if (lastModifier == firstModifier) return; /* Invalid syntax */
362 /* Extract the parameter to play with */
363 if (*lastModifier == '0') {
364 strcpyW(outputparam, context->batchfileW);
365 } else if ((*lastModifier >= '1' && *lastModifier <= '9')) {
367 WCMD_parameter (context -> command, *lastModifier-'0' + context -> shift_count[*lastModifier-'0'],
370 strcpyW(outputparam, forValue);
373 /* So now, firstModifier points to beginning of modifiers, lastModifier
374 points to the variable just after the modifiers. Process modifiers
375 in a specific order, remembering there could be duplicates */
376 modifierLen = lastModifier - firstModifier;
377 finaloutput[0] = 0x00;
379 /* Useful for debugging purposes: */
380 /*printf("Modifier string '%*.*s' and variable is %c\n Param starts as '%s'\n",
381 (modifierLen), (modifierLen), firstModifier, *lastModifier,
384 /* 1. Handle '~' : Strip surrounding quotes */
385 if (outputparam[0]=='"' &&
386 memchrW(firstModifier, '~', modifierLen) != NULL) {
387 int len = strlenW(outputparam);
388 if (outputparam[len-1] == '"') {
389 outputparam[len-1]=0x00;
392 memmove(outputparam, &outputparam[1], (len * sizeof(WCHAR))-1);
395 /* 2. Handle the special case of a $ */
396 if (memchrW(firstModifier, '$', modifierLen) != NULL) {
397 /* Special Case: Search envar specified in $[envvar] for outputparam
398 Note both $ and : are guaranteed otherwise check above would fail */
399 WCHAR *begin = strchrW(firstModifier, '$') + 1;
400 WCHAR *end = strchrW(firstModifier, ':');
402 WCHAR fullpath[MAX_PATH];
404 /* Extract the env var */
405 memcpy(env, begin, (end-begin) * sizeof(WCHAR));
406 env[(end-begin)] = 0x00;
408 /* If env var not found, return empty string */
409 if ((GetEnvironmentVariableW(env, fullpath, MAX_PATH) == 0) ||
410 (SearchPathW(fullpath, outputparam, NULL, MAX_PATH, outputparam, NULL) == 0)) {
411 finaloutput[0] = 0x00;
412 outputparam[0] = 0x00;
413 skipFileParsing = TRUE;
417 /* After this, we need full information on the file,
418 which is valid not to exist. */
419 if (!skipFileParsing) {
420 if (GetFullPathNameW(outputparam, MAX_PATH, fullfilename, NULL) == 0)
423 exists = GetFileAttributesExW(fullfilename, GetFileExInfoStandard,
426 /* 2. Handle 'a' : Output attributes */
428 memchrW(firstModifier, 'a', modifierLen) != NULL) {
430 WCHAR defaults[] = {'-','-','-','-','-','-','-','-','-','\0'};
432 strcpyW(thisoutput, defaults);
433 if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
435 if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
437 if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE)
439 if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
441 if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)
443 if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_COMPRESSED)
445 /* FIXME: What are 6 and 7? */
446 if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
448 strcatW(finaloutput, thisoutput);
451 /* 3. Handle 't' : Date+time */
453 memchrW(firstModifier, 't', modifierLen) != NULL) {
459 if (finaloutput[0] != 0x00) strcatW(finaloutput, space);
461 /* Format the time */
462 FileTimeToSystemTime(&fileInfo.ftLastWriteTime, &systime);
463 GetDateFormatW(LOCALE_USER_DEFAULT, DATE_SHORTDATE, &systime,
464 NULL, thisoutput, MAX_PATH);
465 strcatW(thisoutput, space);
466 datelen = strlenW(thisoutput);
467 GetTimeFormatW(LOCALE_USER_DEFAULT, TIME_NOSECONDS, &systime,
468 NULL, (thisoutput+datelen), MAX_PATH-datelen);
469 strcatW(finaloutput, thisoutput);
472 /* 4. Handle 'z' : File length */
474 memchrW(firstModifier, 'z', modifierLen) != NULL) {
475 /* FIXME: Output full 64 bit size (sprintf does not support I64 here) */
476 ULONG/*64*/ fullsize = /*(fileInfo.nFileSizeHigh << 32) +*/
477 fileInfo.nFileSizeLow;
478 static const WCHAR fmt[] = {'%','u','\0'};
481 if (finaloutput[0] != 0x00) strcatW(finaloutput, space);
482 wsprintfW(thisoutput, fmt, fullsize);
483 strcatW(finaloutput, thisoutput);
486 /* 4. Handle 's' : Use short paths (File doesn't have to exist) */
487 if (memchrW(firstModifier, 's', modifierLen) != NULL) {
488 if (finaloutput[0] != 0x00) strcatW(finaloutput, space);
489 /* Don't flag as doneModifier - %~s on its own is processed later */
490 GetShortPathNameW(outputparam, outputparam, sizeof(outputparam)/sizeof(outputparam[0]));
493 /* 5. Handle 'f' : Fully qualified path (File doesn't have to exist) */
494 /* Note this overrides d,p,n,x */
495 if (memchrW(firstModifier, 'f', modifierLen) != NULL) {
497 if (finaloutput[0] != 0x00) strcatW(finaloutput, space);
498 strcatW(finaloutput, fullfilename);
503 WCHAR fname[MAX_PATH];
505 BOOL doneFileModifier = FALSE;
507 if (finaloutput[0] != 0x00) strcatW(finaloutput, space);
509 /* Split into components */
510 WCMD_splitpath(fullfilename, drive, dir, fname, ext);
512 /* 5. Handle 'd' : Drive Letter */
513 if (memchrW(firstModifier, 'd', modifierLen) != NULL) {
514 strcatW(finaloutput, drive);
516 doneFileModifier = TRUE;
519 /* 6. Handle 'p' : Path */
520 if (memchrW(firstModifier, 'p', modifierLen) != NULL) {
521 strcatW(finaloutput, dir);
523 doneFileModifier = TRUE;
526 /* 7. Handle 'n' : Name */
527 if (memchrW(firstModifier, 'n', modifierLen) != NULL) {
528 strcatW(finaloutput, fname);
530 doneFileModifier = TRUE;
533 /* 8. Handle 'x' : Ext */
534 if (memchrW(firstModifier, 'x', modifierLen) != NULL) {
535 strcatW(finaloutput, ext);
537 doneFileModifier = TRUE;
540 /* If 's' but no other parameter, dump the whole thing */
541 if (!doneFileModifier &&
542 memchrW(firstModifier, 's', modifierLen) != NULL) {
544 if (finaloutput[0] != 0x00) strcatW(finaloutput, space);
545 strcatW(finaloutput, outputparam);
550 /* If No other modifier processed, just add in parameter */
551 if (!doneModifier) strcpyW(finaloutput, outputparam);
553 /* Finish by inserting the replacement into the string */
554 WCMD_strsubstW(*start, lastModifier+1, finaloutput, -1);
557 /*******************************************************************
558 * WCMD_call - processes a batch call statement
560 * If there is a leading ':', calls within this batch program
561 * otherwise launches another program.
563 void WCMD_call (WCHAR *command) {
565 /* Run other program if no leading ':' */
566 if (*command != ':') {
567 WCMD_run_program(command, 1);
570 WCHAR gotoLabel[MAX_PATH];
572 strcpyW(gotoLabel, param1);
578 /* Save the current file position, call the same file,
581 li.u.LowPart = SetFilePointer(context -> h, li.u.LowPart,
582 &li.u.HighPart, FILE_CURRENT);
584 WCMD_batch (param1, command, 1, gotoLabel, context->h);
586 SetFilePointer(context -> h, li.u.LowPart,
587 &li.u.HighPart, FILE_BEGIN);
589 WCMD_output_asis( WCMD_LoadMessage(WCMD_CALLINSCRIPT));