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, FALSE))
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 * Get one line from a batch file/console. We can't use the native f* functions because
180 * of the filename syntax differences between DOS and Unix. Also need to lose
181 * the LF (or CRLF) from the line.
184 WCHAR *WCMD_fgets(WCHAR *s, int noChars, HANDLE h, BOOL is_console_handle)
186 DWORD bytes, charsRead;
191 if (is_console_handle) {
192 status = ReadConsoleW(h, s, noChars, &charsRead, NULL);
193 if (!status) return NULL;
194 s[charsRead-2] = '\0'; /* Strip \r\n */
198 /* TODO: More intelligent buffering for reading lines from files */
200 status = WCMD_ReadFile(h, s, 1, &bytes);
201 if ((status == 0) || ((bytes == 0) && (s == p))) return NULL;
202 if (*s == '\n') bytes = 0;
203 else if (*s != '\r') {
208 } while ((bytes == 1) && (noChars > 1));
212 /* WCMD_splitpath - copied from winefile as no obvious way to use it otherwise */
213 void WCMD_splitpath(const WCHAR* path, WCHAR* drv, WCHAR* dir, WCHAR* name, WCHAR* ext)
215 const WCHAR* end; /* end of processed string */
216 const WCHAR* p; /* search pointer */
217 const WCHAR* s; /* copy pointer */
219 /* extract drive name */
220 if (path[0] && path[1]==':') {
229 end = path + strlenW(path);
231 /* search for begin of file extension */
232 for(p=end; p>path && *--p!='\\' && *p!='/'; )
239 for(s=end; (*ext=*s++); )
242 /* search for end of directory name */
244 if (*--p=='\\' || *p=='/') {
264 /****************************************************************************
265 * WCMD_HandleTildaModifiers
267 * Handle the ~ modifiers when expanding %0-9 or (%a-z in for command)
268 * %~xxxxxV (V=0-9 or A-Z)
269 * Where xxxx is any combination of:
271 * f - Fully qualified path (assumes current dir if not drive\dir)
276 * s - path with shortnames
280 * $ENVVAR: - Searches ENVVAR for (contents of V) and expands to fully
283 * To work out the length of the modifier:
285 * Note: In the case of %0-9 knowing the end of the modifier is easy,
286 * but in a for loop, the for end WCHARacter may also be a modifier
287 * eg. for %a in (c:\a.a) do echo XXX
288 * where XXX = %~a (just ~)
289 * %~aa (~ and attributes)
290 * %~aaxa (~, attributes and extension)
291 * BUT %~aax (~ and attributes followed by 'x')
293 * Hence search forwards until find an invalid modifier, and then
294 * backwards until find for variable or 0-9
296 void WCMD_HandleTildaModifiers(WCHAR **start, const WCHAR *forVariable,
297 const WCHAR *forValue, BOOL justFors) {
299 #define NUMMODIFIERS 11
300 static const WCHAR validmodifiers[NUMMODIFIERS] = {
301 '~', 'f', 'd', 'p', 'n', 'x', 's', 'a', 't', 'z', '$'
303 static const WCHAR space[] = {' ', '\0'};
305 WIN32_FILE_ATTRIBUTE_DATA fileInfo;
306 WCHAR outputparam[MAX_PATH];
307 WCHAR finaloutput[MAX_PATH];
308 WCHAR fullfilename[MAX_PATH];
309 WCHAR thisoutput[MAX_PATH];
310 WCHAR *pos = *start+1;
311 WCHAR *firstModifier = pos;
312 WCHAR *lastModifier = NULL;
314 BOOL finished = FALSE;
317 BOOL skipFileParsing = FALSE;
318 BOOL doneModifier = FALSE;
320 /* Search forwards until find invalid character modifier */
323 /* Work on the previous character */
324 if (lastModifier != NULL) {
326 for (i=0; i<NUMMODIFIERS; i++) {
327 if (validmodifiers[i] == *lastModifier) {
329 /* Special case '$' to skip until : found */
330 if (*lastModifier == '$') {
331 while (*pos != ':' && *pos) pos++;
332 if (*pos == 0x00) return; /* Invalid syntax */
333 pos++; /* Skip ':' */
339 if (i==NUMMODIFIERS) {
344 /* Save this one away */
351 while (lastModifier > firstModifier) {
352 WINE_TRACE("Looking backwards for parameter id: %s / %s\n",
353 wine_dbgstr_w(lastModifier), wine_dbgstr_w(forVariable));
355 if (!justFors && context && (*lastModifier >= '0' && *lastModifier <= '9')) {
356 /* Its a valid parameter identifier - OK */
359 } else if (forVariable && *lastModifier == *(forVariable+1)) {
360 /* Its a valid parameter identifier - OK */
367 if (lastModifier == firstModifier) return; /* Invalid syntax */
369 /* Extract the parameter to play with */
370 if (*lastModifier == '0') {
371 strcpyW(outputparam, context->batchfileW);
372 } else if ((*lastModifier >= '1' && *lastModifier <= '9')) {
374 WCMD_parameter (context -> command, *lastModifier-'0' + context -> shift_count[*lastModifier-'0'],
377 strcpyW(outputparam, forValue);
380 /* So now, firstModifier points to beginning of modifiers, lastModifier
381 points to the variable just after the modifiers. Process modifiers
382 in a specific order, remembering there could be duplicates */
383 modifierLen = lastModifier - firstModifier;
384 finaloutput[0] = 0x00;
386 /* Useful for debugging purposes: */
387 /*printf("Modifier string '%*.*s' and variable is %c\n Param starts as '%s'\n",
388 (modifierLen), (modifierLen), firstModifier, *lastModifier,
391 /* 1. Handle '~' : Strip surrounding quotes */
392 if (outputparam[0]=='"' &&
393 memchrW(firstModifier, '~', modifierLen) != NULL) {
394 int len = strlenW(outputparam);
395 if (outputparam[len-1] == '"') {
396 outputparam[len-1]=0x00;
399 memmove(outputparam, &outputparam[1], (len * sizeof(WCHAR))-1);
402 /* 2. Handle the special case of a $ */
403 if (memchrW(firstModifier, '$', modifierLen) != NULL) {
404 /* Special Case: Search envar specified in $[envvar] for outputparam
405 Note both $ and : are guaranteed otherwise check above would fail */
406 WCHAR *begin = strchrW(firstModifier, '$') + 1;
407 WCHAR *end = strchrW(firstModifier, ':');
409 WCHAR fullpath[MAX_PATH];
411 /* Extract the env var */
412 memcpy(env, begin, (end-begin) * sizeof(WCHAR));
413 env[(end-begin)] = 0x00;
415 /* If env var not found, return empty string */
416 if ((GetEnvironmentVariableW(env, fullpath, MAX_PATH) == 0) ||
417 (SearchPathW(fullpath, outputparam, NULL, MAX_PATH, outputparam, NULL) == 0)) {
418 finaloutput[0] = 0x00;
419 outputparam[0] = 0x00;
420 skipFileParsing = TRUE;
424 /* After this, we need full information on the file,
425 which is valid not to exist. */
426 if (!skipFileParsing) {
427 if (GetFullPathNameW(outputparam, MAX_PATH, fullfilename, NULL) == 0)
430 exists = GetFileAttributesExW(fullfilename, GetFileExInfoStandard,
433 /* 2. Handle 'a' : Output attributes */
435 memchrW(firstModifier, 'a', modifierLen) != NULL) {
437 WCHAR defaults[] = {'-','-','-','-','-','-','-','-','-','\0'};
439 strcpyW(thisoutput, defaults);
440 if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
442 if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
444 if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE)
446 if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
448 if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)
450 if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_COMPRESSED)
452 /* FIXME: What are 6 and 7? */
453 if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
455 strcatW(finaloutput, thisoutput);
458 /* 3. Handle 't' : Date+time */
460 memchrW(firstModifier, 't', modifierLen) != NULL) {
466 if (finaloutput[0] != 0x00) strcatW(finaloutput, space);
468 /* Format the time */
469 FileTimeToSystemTime(&fileInfo.ftLastWriteTime, &systime);
470 GetDateFormatW(LOCALE_USER_DEFAULT, DATE_SHORTDATE, &systime,
471 NULL, thisoutput, MAX_PATH);
472 strcatW(thisoutput, space);
473 datelen = strlenW(thisoutput);
474 GetTimeFormatW(LOCALE_USER_DEFAULT, TIME_NOSECONDS, &systime,
475 NULL, (thisoutput+datelen), MAX_PATH-datelen);
476 strcatW(finaloutput, thisoutput);
479 /* 4. Handle 'z' : File length */
481 memchrW(firstModifier, 'z', modifierLen) != NULL) {
482 /* FIXME: Output full 64 bit size (sprintf does not support I64 here) */
483 ULONG/*64*/ fullsize = /*(fileInfo.nFileSizeHigh << 32) +*/
484 fileInfo.nFileSizeLow;
485 static const WCHAR fmt[] = {'%','u','\0'};
488 if (finaloutput[0] != 0x00) strcatW(finaloutput, space);
489 wsprintfW(thisoutput, fmt, fullsize);
490 strcatW(finaloutput, thisoutput);
493 /* 4. Handle 's' : Use short paths (File doesn't have to exist) */
494 if (memchrW(firstModifier, 's', modifierLen) != NULL) {
495 if (finaloutput[0] != 0x00) strcatW(finaloutput, space);
496 /* Don't flag as doneModifier - %~s on its own is processed later */
497 GetShortPathNameW(outputparam, outputparam, sizeof(outputparam)/sizeof(outputparam[0]));
500 /* 5. Handle 'f' : Fully qualified path (File doesn't have to exist) */
501 /* Note this overrides d,p,n,x */
502 if (memchrW(firstModifier, 'f', modifierLen) != NULL) {
504 if (finaloutput[0] != 0x00) strcatW(finaloutput, space);
505 strcatW(finaloutput, fullfilename);
510 WCHAR fname[MAX_PATH];
512 BOOL doneFileModifier = FALSE;
514 if (finaloutput[0] != 0x00) strcatW(finaloutput, space);
516 /* Split into components */
517 WCMD_splitpath(fullfilename, drive, dir, fname, ext);
519 /* 5. Handle 'd' : Drive Letter */
520 if (memchrW(firstModifier, 'd', modifierLen) != NULL) {
521 strcatW(finaloutput, drive);
523 doneFileModifier = TRUE;
526 /* 6. Handle 'p' : Path */
527 if (memchrW(firstModifier, 'p', modifierLen) != NULL) {
528 strcatW(finaloutput, dir);
530 doneFileModifier = TRUE;
533 /* 7. Handle 'n' : Name */
534 if (memchrW(firstModifier, 'n', modifierLen) != NULL) {
535 strcatW(finaloutput, fname);
537 doneFileModifier = TRUE;
540 /* 8. Handle 'x' : Ext */
541 if (memchrW(firstModifier, 'x', modifierLen) != NULL) {
542 strcatW(finaloutput, ext);
544 doneFileModifier = TRUE;
547 /* If 's' but no other parameter, dump the whole thing */
548 if (!doneFileModifier &&
549 memchrW(firstModifier, 's', modifierLen) != NULL) {
551 if (finaloutput[0] != 0x00) strcatW(finaloutput, space);
552 strcatW(finaloutput, outputparam);
557 /* If No other modifier processed, just add in parameter */
558 if (!doneModifier) strcpyW(finaloutput, outputparam);
560 /* Finish by inserting the replacement into the string */
561 WCMD_strsubstW(*start, lastModifier+1, finaloutput, -1);
564 /*******************************************************************
565 * WCMD_call - processes a batch call statement
567 * If there is a leading ':', calls within this batch program
568 * otherwise launches another program.
570 void WCMD_call (WCHAR *command) {
572 /* Run other program if no leading ':' */
573 if (*command != ':') {
574 WCMD_run_program(command, 1);
577 WCHAR gotoLabel[MAX_PATH];
579 strcpyW(gotoLabel, param1);
585 /* Save the current file position, call the same file,
588 li.u.LowPart = SetFilePointer(context -> h, li.u.LowPart,
589 &li.u.HighPart, FILE_CURRENT);
591 WCMD_batch (param1, command, 1, gotoLabel, context->h);
593 SetFilePointer(context -> h, li.u.LowPart,
594 &li.u.HighPart, FILE_BEGIN);
596 WCMD_output_asis_stderr(WCMD_LoadMessage(WCMD_CALLINSCRIPT));