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);
27 extern WCHAR quals[MAX_PATH], param1[MAX_PATH], param2[MAX_PATH];
28 extern BATCH_CONTEXT *context;
29 extern DWORD errorlevel;
31 /****************************************************************************
34 * Open and execute a batch file.
35 * On entry *command includes the complete command line beginning with the name
36 * of the batch file (if a CALL command was entered the CALL has been removed).
37 * *file is the name of the file, which might not exist and may not have the
38 * .BAT suffix on. Called is 1 for a CALL, 0 otherwise.
40 * We need to handle recursion correctly, since one batch program might call another.
41 * So parameters for this batch file are held in a BATCH_CONTEXT structure.
43 * To support call within the same batch program, another input parameter is
44 * a label to goto once opened.
47 void WCMD_batch (WCHAR *file, WCHAR *command, int called, WCHAR *startLabel, HANDLE pgmHandle) {
49 HANDLE h = INVALID_HANDLE_VALUE;
50 BATCH_CONTEXT *prev_context;
52 if (startLabel == NULL) {
53 h = CreateFileW (file, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
54 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
55 if (h == INVALID_HANDLE_VALUE) {
56 SetLastError (ERROR_FILE_NOT_FOUND);
61 DuplicateHandle(GetCurrentProcess(), pgmHandle,
62 GetCurrentProcess(), &h,
63 0, FALSE, DUPLICATE_SAME_ACCESS);
67 * Create a context structure for this batch file.
70 prev_context = context;
71 context = LocalAlloc (LMEM_FIXED, sizeof (BATCH_CONTEXT));
73 context->batchfileW = WCMD_strdupW(file);
74 context -> command = command;
75 memset(context -> shift_count, 0x00, sizeof(context -> shift_count));
76 context -> prev_context = prev_context;
77 context -> skip_rest = FALSE;
79 /* If processing a call :label, 'goto' the label in question */
81 strcpyW(param1, startLabel);
86 * Work through the file line by line. Specific batch commands are processed here,
87 * the rest are handled by the main command processor.
90 while (context -> skip_rest == FALSE) {
91 CMD_LIST *toExecute = NULL; /* Commands left to be executed */
92 if (!WCMD_ReadAndParseLine(NULL, &toExecute, h))
94 WCMD_process_commands(toExecute, FALSE, NULL, NULL);
95 WCMD_free_commands(toExecute);
101 * If invoked by a CALL, we return to the context of our caller. Otherwise return
102 * to the caller's caller.
105 HeapFree(GetProcessHeap(), 0, context->batchfileW);
107 if ((prev_context != NULL) && (!called)) {
108 prev_context -> skip_rest = TRUE;
109 context = prev_context;
111 context = prev_context;
114 /*******************************************************************
117 * Extracts a delimited parameter from an input string
120 * s [I] input string, non NULL
121 * n [I] # of the (possibly double quotes-delimited) parameter to return
123 * where [O] if non NULL, pointer to the start of the nth parameter in s,
124 * potentially a " character
125 * end [O] if non NULL, pointer to the last char of
126 * the nth parameter in s, potentially a " character
129 * Success: Returns the nth delimited parameter found in s.
130 * *where points to the start of the param, possibly a starting
131 * double quotes character
132 * Failure: Returns an empty string if the param is not found.
133 * *where is set to NULL
136 * Return value is stored in static storage, hence is overwritten
138 * Doesn't include any potentially delimiting double quotes
140 WCHAR *WCMD_parameter (WCHAR *s, int n, WCHAR **where, WCHAR **end) {
142 static WCHAR param[MAX_PATH];
144 BOOL quotesDelimited;
146 if (where != NULL) *where = NULL;
147 if (end != NULL) *end = NULL;
150 while (*p && ((*p == ' ') || (*p == ',') || (*p == '=') || (*p == '\t')))
152 if (*p == '\0') return param;
154 quotesDelimited = (*p == '"');
155 if (where != NULL && curParamNb == n) *where = p;
157 if (quotesDelimited) {
159 while (*p && *p != '"') p++;
162 while (*p && (*p != ' ') && (*p != ',') && (*p != '=') && (*p != '\t'))
165 if (curParamNb == n) {
166 memcpy(param, q, (p - q) * sizeof(WCHAR));
168 if (end) *end = p - 1 + quotesDelimited;
171 if (quotesDelimited && *p == '"') p++;
176 /****************************************************************************
179 * Gets one line from a file/console and puts it into buffer buf
180 * Pre: buf has size noChars
181 * 1 <= noChars <= MAXSTRING
182 * Post: buf is filled with at most noChars-1 characters, and gets nul-terminated
183 buf does not include EOL terminator
186 * NULL on error or EOF
189 WCHAR *WCMD_fgets(WCHAR *buf, int noChars, HANDLE h)
193 LARGE_INTEGER filepos;
196 /* We can't use the native f* functions because of the filename syntax differences
197 between DOS and Unix. Also need to lose the LF (or CRLF) from the line. */
199 if (!WCMD_is_console_handle(h)) {
200 /* Save current file position */
201 filepos.QuadPart = 0;
202 SetFilePointerEx(h, filepos, &filepos, FILE_CURRENT);
205 status = WCMD_ReadFile(h, buf, noChars, &charsRead);
206 if (!status || charsRead == 0) return NULL;
209 for (i = 0; i < charsRead; i++) {
210 if (buf[i] == '\n' || buf[i] == '\r')
214 if (!WCMD_is_console_handle(h) && i != charsRead) {
215 /* Sets file pointer to the start of the next line, if any */
216 filepos.QuadPart += i + 1 + (buf[i] == '\r' ? 1 : 0);
217 SetFilePointerEx(h, filepos, NULL, FILE_BEGIN);
220 /* Truncate at EOL (or end of buffer) */
229 /* WCMD_splitpath - copied from winefile as no obvious way to use it otherwise */
230 void WCMD_splitpath(const WCHAR* path, WCHAR* drv, WCHAR* dir, WCHAR* name, WCHAR* ext)
232 const WCHAR* end; /* end of processed string */
233 const WCHAR* p; /* search pointer */
234 const WCHAR* s; /* copy pointer */
236 /* extract drive name */
237 if (path[0] && path[1]==':') {
246 end = path + strlenW(path);
248 /* search for begin of file extension */
249 for(p=end; p>path && *--p!='\\' && *p!='/'; )
256 for(s=end; (*ext=*s++); )
259 /* search for end of directory name */
261 if (*--p=='\\' || *p=='/') {
281 /****************************************************************************
282 * WCMD_HandleTildaModifiers
284 * Handle the ~ modifiers when expanding %0-9 or (%a-z in for command)
285 * %~xxxxxV (V=0-9 or A-Z)
286 * Where xxxx is any combination of:
288 * f - Fully qualified path (assumes current dir if not drive\dir)
293 * s - path with shortnames
297 * $ENVVAR: - Searches ENVVAR for (contents of V) and expands to fully
300 * To work out the length of the modifier:
302 * Note: In the case of %0-9 knowing the end of the modifier is easy,
303 * but in a for loop, the for end WCHARacter may also be a modifier
304 * eg. for %a in (c:\a.a) do echo XXX
305 * where XXX = %~a (just ~)
306 * %~aa (~ and attributes)
307 * %~aaxa (~, attributes and extension)
308 * BUT %~aax (~ and attributes followed by 'x')
310 * Hence search forwards until find an invalid modifier, and then
311 * backwards until find for variable or 0-9
313 void WCMD_HandleTildaModifiers(WCHAR **start, const WCHAR *forVariable,
314 const WCHAR *forValue, BOOL justFors) {
316 #define NUMMODIFIERS 11
317 static const WCHAR validmodifiers[NUMMODIFIERS] = {
318 '~', 'f', 'd', 'p', 'n', 'x', 's', 'a', 't', 'z', '$'
320 static const WCHAR space[] = {' ', '\0'};
322 WIN32_FILE_ATTRIBUTE_DATA fileInfo;
323 WCHAR outputparam[MAX_PATH];
324 WCHAR finaloutput[MAX_PATH];
325 WCHAR fullfilename[MAX_PATH];
326 WCHAR thisoutput[MAX_PATH];
327 WCHAR *pos = *start+1;
328 WCHAR *firstModifier = pos;
329 WCHAR *lastModifier = NULL;
331 BOOL finished = FALSE;
334 BOOL skipFileParsing = FALSE;
335 BOOL doneModifier = FALSE;
337 /* Search forwards until find invalid character modifier */
340 /* Work on the previous character */
341 if (lastModifier != NULL) {
343 for (i=0; i<NUMMODIFIERS; i++) {
344 if (validmodifiers[i] == *lastModifier) {
346 /* Special case '$' to skip until : found */
347 if (*lastModifier == '$') {
348 while (*pos != ':' && *pos) pos++;
349 if (*pos == 0x00) return; /* Invalid syntax */
350 pos++; /* Skip ':' */
356 if (i==NUMMODIFIERS) {
361 /* Save this one away */
368 while (lastModifier > firstModifier) {
369 WINE_TRACE("Looking backwards for parameter id: %s / %s\n",
370 wine_dbgstr_w(lastModifier), wine_dbgstr_w(forVariable));
372 if (!justFors && context && (*lastModifier >= '0' && *lastModifier <= '9')) {
373 /* Its a valid parameter identifier - OK */
376 } else if (forVariable && *lastModifier == *(forVariable+1)) {
377 /* Its a valid parameter identifier - OK */
384 if (lastModifier == firstModifier) return; /* Invalid syntax */
386 /* Extract the parameter to play with */
387 if (*lastModifier == '0') {
388 strcpyW(outputparam, context->batchfileW);
389 } else if ((*lastModifier >= '1' && *lastModifier <= '9')) {
391 WCMD_parameter (context -> command, *lastModifier-'0' + context -> shift_count[*lastModifier-'0'],
394 strcpyW(outputparam, forValue);
397 /* So now, firstModifier points to beginning of modifiers, lastModifier
398 points to the variable just after the modifiers. Process modifiers
399 in a specific order, remembering there could be duplicates */
400 modifierLen = lastModifier - firstModifier;
401 finaloutput[0] = 0x00;
403 /* Useful for debugging purposes: */
404 /*printf("Modifier string '%*.*s' and variable is %c\n Param starts as '%s'\n",
405 (modifierLen), (modifierLen), firstModifier, *lastModifier,
408 /* 1. Handle '~' : Strip surrounding quotes */
409 if (outputparam[0]=='"' &&
410 memchrW(firstModifier, '~', modifierLen) != NULL) {
411 int len = strlenW(outputparam);
412 if (outputparam[len-1] == '"') {
413 outputparam[len-1]=0x00;
416 memmove(outputparam, &outputparam[1], (len * sizeof(WCHAR))-1);
419 /* 2. Handle the special case of a $ */
420 if (memchrW(firstModifier, '$', modifierLen) != NULL) {
421 /* Special Case: Search envar specified in $[envvar] for outputparam
422 Note both $ and : are guaranteed otherwise check above would fail */
423 WCHAR *begin = strchrW(firstModifier, '$') + 1;
424 WCHAR *end = strchrW(firstModifier, ':');
426 WCHAR fullpath[MAX_PATH];
428 /* Extract the env var */
429 memcpy(env, begin, (end-begin) * sizeof(WCHAR));
430 env[(end-begin)] = 0x00;
432 /* If env var not found, return empty string */
433 if ((GetEnvironmentVariableW(env, fullpath, MAX_PATH) == 0) ||
434 (SearchPathW(fullpath, outputparam, NULL, MAX_PATH, outputparam, NULL) == 0)) {
435 finaloutput[0] = 0x00;
436 outputparam[0] = 0x00;
437 skipFileParsing = TRUE;
441 /* After this, we need full information on the file,
442 which is valid not to exist. */
443 if (!skipFileParsing) {
444 if (GetFullPathNameW(outputparam, MAX_PATH, fullfilename, NULL) == 0)
447 exists = GetFileAttributesExW(fullfilename, GetFileExInfoStandard,
450 /* 2. Handle 'a' : Output attributes */
452 memchrW(firstModifier, 'a', modifierLen) != NULL) {
454 WCHAR defaults[] = {'-','-','-','-','-','-','-','-','-','\0'};
456 strcpyW(thisoutput, defaults);
457 if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
459 if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
461 if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE)
463 if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
465 if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)
467 if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_COMPRESSED)
469 /* FIXME: What are 6 and 7? */
470 if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
472 strcatW(finaloutput, thisoutput);
475 /* 3. Handle 't' : Date+time */
477 memchrW(firstModifier, 't', modifierLen) != NULL) {
483 if (finaloutput[0] != 0x00) strcatW(finaloutput, space);
485 /* Format the time */
486 FileTimeToSystemTime(&fileInfo.ftLastWriteTime, &systime);
487 GetDateFormatW(LOCALE_USER_DEFAULT, DATE_SHORTDATE, &systime,
488 NULL, thisoutput, MAX_PATH);
489 strcatW(thisoutput, space);
490 datelen = strlenW(thisoutput);
491 GetTimeFormatW(LOCALE_USER_DEFAULT, TIME_NOSECONDS, &systime,
492 NULL, (thisoutput+datelen), MAX_PATH-datelen);
493 strcatW(finaloutput, thisoutput);
496 /* 4. Handle 'z' : File length */
498 memchrW(firstModifier, 'z', modifierLen) != NULL) {
499 /* FIXME: Output full 64 bit size (sprintf does not support I64 here) */
500 ULONG/*64*/ fullsize = /*(fileInfo.nFileSizeHigh << 32) +*/
501 fileInfo.nFileSizeLow;
502 static const WCHAR fmt[] = {'%','u','\0'};
505 if (finaloutput[0] != 0x00) strcatW(finaloutput, space);
506 wsprintfW(thisoutput, fmt, fullsize);
507 strcatW(finaloutput, thisoutput);
510 /* 4. Handle 's' : Use short paths (File doesn't have to exist) */
511 if (memchrW(firstModifier, 's', modifierLen) != NULL) {
512 if (finaloutput[0] != 0x00) strcatW(finaloutput, space);
513 /* Don't flag as doneModifier - %~s on its own is processed later */
514 GetShortPathNameW(outputparam, outputparam, sizeof(outputparam)/sizeof(outputparam[0]));
517 /* 5. Handle 'f' : Fully qualified path (File doesn't have to exist) */
518 /* Note this overrides d,p,n,x */
519 if (memchrW(firstModifier, 'f', modifierLen) != NULL) {
521 if (finaloutput[0] != 0x00) strcatW(finaloutput, space);
522 strcatW(finaloutput, fullfilename);
527 WCHAR fname[MAX_PATH];
529 BOOL doneFileModifier = FALSE;
531 if (finaloutput[0] != 0x00) strcatW(finaloutput, space);
533 /* Split into components */
534 WCMD_splitpath(fullfilename, drive, dir, fname, ext);
536 /* 5. Handle 'd' : Drive Letter */
537 if (memchrW(firstModifier, 'd', modifierLen) != NULL) {
538 strcatW(finaloutput, drive);
540 doneFileModifier = TRUE;
543 /* 6. Handle 'p' : Path */
544 if (memchrW(firstModifier, 'p', modifierLen) != NULL) {
545 strcatW(finaloutput, dir);
547 doneFileModifier = TRUE;
550 /* 7. Handle 'n' : Name */
551 if (memchrW(firstModifier, 'n', modifierLen) != NULL) {
552 strcatW(finaloutput, fname);
554 doneFileModifier = TRUE;
557 /* 8. Handle 'x' : Ext */
558 if (memchrW(firstModifier, 'x', modifierLen) != NULL) {
559 strcatW(finaloutput, ext);
561 doneFileModifier = TRUE;
564 /* If 's' but no other parameter, dump the whole thing */
565 if (!doneFileModifier &&
566 memchrW(firstModifier, 's', modifierLen) != NULL) {
568 if (finaloutput[0] != 0x00) strcatW(finaloutput, space);
569 strcatW(finaloutput, outputparam);
574 /* If No other modifier processed, just add in parameter */
575 if (!doneModifier) strcpyW(finaloutput, outputparam);
577 /* Finish by inserting the replacement into the string */
578 WCMD_strsubstW(*start, lastModifier+1, finaloutput, -1);
581 /*******************************************************************
582 * WCMD_call - processes a batch call statement
584 * If there is a leading ':', calls within this batch program
585 * otherwise launches another program.
587 void WCMD_call (WCHAR *command) {
589 /* Run other program if no leading ':' */
590 if (*command != ':') {
591 WCMD_run_program(command, 1);
594 WCHAR gotoLabel[MAX_PATH];
596 strcpyW(gotoLabel, param1);
602 /* Save the current file position, call the same file,
605 li.u.LowPart = SetFilePointer(context -> h, li.u.LowPart,
606 &li.u.HighPart, FILE_CURRENT);
608 WCMD_batch (param1, command, 1, gotoLabel, context->h);
610 SetFilePointer(context -> h, li.u.LowPart,
611 &li.u.HighPart, FILE_BEGIN);
613 WCMD_output_asis_stderr(WCMD_LoadMessage(WCMD_CALLINSCRIPT));