cmd: Output error messages to stderr where appropriate.
[wine.git] / programs / cmd / batch.c
blob800f05eceae89efb78fef0c20ba9fd535f82281f
1 /*
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
22 #include "wcmd.h"
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 /****************************************************************************
32 * WCMD_batch
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);
57 WCMD_print_error ();
58 return;
60 } else {
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));
72 context -> h = h;
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 */
80 if (startLabel) {
81 strcpyW(param1, startLabel);
82 WCMD_goto(NULL);
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) == NULL)
93 break;
94 WCMD_process_commands(toExecute, FALSE, NULL, NULL);
95 WCMD_free_commands(toExecute);
96 toExecute = NULL;
98 CloseHandle (h);
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);
106 LocalFree (context);
107 if ((prev_context != NULL) && (!called)) {
108 prev_context -> skip_rest = TRUE;
109 context = prev_context;
111 context = prev_context;
114 /*******************************************************************
115 * WCMD_parameter
117 * Extracts a delimited parameter from an input string
119 * PARAMS
120 * s [I] input string, non NULL
121 * n [I] # of the (possibly double quotes-delimited) parameter to return
122 * Starts at 0
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
128 * RETURNS
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
135 * NOTES
136 * Return value is stored in static storage, hence is overwritten
137 * after each call.
138 * Doesn't include any potentially delimiting double quotes
140 WCHAR *WCMD_parameter (WCHAR *s, int n, WCHAR **where, WCHAR **end) {
141 int curParamNb = 0;
142 static WCHAR param[MAX_PATH];
143 WCHAR *p = s, *q;
144 BOOL quotesDelimited;
146 if (where != NULL) *where = NULL;
147 if (end != NULL) *end = NULL;
148 param[0] = '\0';
149 while (TRUE) {
150 while (*p && ((*p == ' ') || (*p == ',') || (*p == '=') || (*p == '\t')))
151 p++;
152 if (*p == '\0') return param;
154 quotesDelimited = (*p == '"');
155 if (where != NULL && curParamNb == n) *where = p;
157 if (quotesDelimited) {
158 q = ++p;
159 while (*p && *p != '"') p++;
160 } else {
161 q = p;
162 while (*p && (*p != ' ') && (*p != ',') && (*p != '=') && (*p != '\t'))
163 p++;
165 if (curParamNb == n) {
166 memcpy(param, q, (p - q) * sizeof(WCHAR));
167 param[p-q] = '\0';
168 if (end) *end = p - 1 + quotesDelimited;
169 return param;
171 if (quotesDelimited && *p == '"') p++;
172 curParamNb++;
176 /****************************************************************************
177 * WCMD_fgets
179 * Get one line from a batch file. 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) {
186 DWORD bytes;
187 BOOL status;
188 WCHAR *p;
190 p = s;
191 do {
192 status = WCMD_ReadFile (h, s, 1, &bytes, NULL);
193 if ((status == 0) || ((bytes == 0) && (s == p))) return NULL;
194 if (*s == '\n') bytes = 0;
195 else if (*s != '\r') {
196 s++;
197 noChars--;
199 *s = '\0';
200 } while ((bytes == 1) && (noChars > 1));
201 return p;
204 /* WCMD_splitpath - copied from winefile as no obvious way to use it otherwise */
205 void WCMD_splitpath(const WCHAR* path, WCHAR* drv, WCHAR* dir, WCHAR* name, WCHAR* ext)
207 const WCHAR* end; /* end of processed string */
208 const WCHAR* p; /* search pointer */
209 const WCHAR* s; /* copy pointer */
211 /* extract drive name */
212 if (path[0] && path[1]==':') {
213 if (drv) {
214 *drv++ = *path++;
215 *drv++ = *path++;
216 *drv = '\0';
218 } else if (drv)
219 *drv = '\0';
221 end = path + strlenW(path);
223 /* search for begin of file extension */
224 for(p=end; p>path && *--p!='\\' && *p!='/'; )
225 if (*p == '.') {
226 end = p;
227 break;
230 if (ext)
231 for(s=end; (*ext=*s++); )
232 ext++;
234 /* search for end of directory name */
235 for(p=end; p>path; )
236 if (*--p=='\\' || *p=='/') {
237 p++;
238 break;
241 if (name) {
242 for(s=p; s<end; )
243 *name++ = *s++;
245 *name = '\0';
248 if (dir) {
249 for(s=path; s<p; )
250 *dir++ = *s++;
252 *dir = '\0';
256 /****************************************************************************
257 * WCMD_HandleTildaModifiers
259 * Handle the ~ modifiers when expanding %0-9 or (%a-z in for command)
260 * %~xxxxxV (V=0-9 or A-Z)
261 * Where xxxx is any combination of:
262 * ~ - Removes quotes
263 * f - Fully qualified path (assumes current dir if not drive\dir)
264 * d - drive letter
265 * p - path
266 * n - filename
267 * x - file extension
268 * s - path with shortnames
269 * a - attributes
270 * t - date/time
271 * z - size
272 * $ENVVAR: - Searches ENVVAR for (contents of V) and expands to fully
273 * qualified path
275 * To work out the length of the modifier:
277 * Note: In the case of %0-9 knowing the end of the modifier is easy,
278 * but in a for loop, the for end WCHARacter may also be a modifier
279 * eg. for %a in (c:\a.a) do echo XXX
280 * where XXX = %~a (just ~)
281 * %~aa (~ and attributes)
282 * %~aaxa (~, attributes and extension)
283 * BUT %~aax (~ and attributes followed by 'x')
285 * Hence search forwards until find an invalid modifier, and then
286 * backwards until find for variable or 0-9
288 void WCMD_HandleTildaModifiers(WCHAR **start, const WCHAR *forVariable,
289 const WCHAR *forValue, BOOL justFors) {
291 #define NUMMODIFIERS 11
292 static const WCHAR validmodifiers[NUMMODIFIERS] = {
293 '~', 'f', 'd', 'p', 'n', 'x', 's', 'a', 't', 'z', '$'
295 static const WCHAR space[] = {' ', '\0'};
297 WIN32_FILE_ATTRIBUTE_DATA fileInfo;
298 WCHAR outputparam[MAX_PATH];
299 WCHAR finaloutput[MAX_PATH];
300 WCHAR fullfilename[MAX_PATH];
301 WCHAR thisoutput[MAX_PATH];
302 WCHAR *pos = *start+1;
303 WCHAR *firstModifier = pos;
304 WCHAR *lastModifier = NULL;
305 int modifierLen = 0;
306 BOOL finished = FALSE;
307 int i = 0;
308 BOOL exists = TRUE;
309 BOOL skipFileParsing = FALSE;
310 BOOL doneModifier = FALSE;
312 /* Search forwards until find invalid character modifier */
313 while (!finished) {
315 /* Work on the previous character */
316 if (lastModifier != NULL) {
318 for (i=0; i<NUMMODIFIERS; i++) {
319 if (validmodifiers[i] == *lastModifier) {
321 /* Special case '$' to skip until : found */
322 if (*lastModifier == '$') {
323 while (*pos != ':' && *pos) pos++;
324 if (*pos == 0x00) return; /* Invalid syntax */
325 pos++; /* Skip ':' */
327 break;
331 if (i==NUMMODIFIERS) {
332 finished = TRUE;
336 /* Save this one away */
337 if (!finished) {
338 lastModifier = pos;
339 pos++;
343 while (lastModifier > firstModifier) {
344 WINE_TRACE("Looking backwards for parameter id: %s / %s\n",
345 wine_dbgstr_w(lastModifier), wine_dbgstr_w(forVariable));
347 if (!justFors && context && (*lastModifier >= '0' && *lastModifier <= '9')) {
348 /* Its a valid parameter identifier - OK */
349 break;
351 } else if (forVariable && *lastModifier == *(forVariable+1)) {
352 /* Its a valid parameter identifier - OK */
353 break;
355 } else {
356 lastModifier--;
359 if (lastModifier == firstModifier) return; /* Invalid syntax */
361 /* Extract the parameter to play with */
362 if (*lastModifier == '0') {
363 strcpyW(outputparam, context->batchfileW);
364 } else if ((*lastModifier >= '1' && *lastModifier <= '9')) {
365 strcpyW(outputparam,
366 WCMD_parameter (context -> command, *lastModifier-'0' + context -> shift_count[*lastModifier-'0'],
367 NULL, NULL));
368 } else {
369 strcpyW(outputparam, forValue);
372 /* So now, firstModifier points to beginning of modifiers, lastModifier
373 points to the variable just after the modifiers. Process modifiers
374 in a specific order, remembering there could be duplicates */
375 modifierLen = lastModifier - firstModifier;
376 finaloutput[0] = 0x00;
378 /* Useful for debugging purposes: */
379 /*printf("Modifier string '%*.*s' and variable is %c\n Param starts as '%s'\n",
380 (modifierLen), (modifierLen), firstModifier, *lastModifier,
381 outputparam);*/
383 /* 1. Handle '~' : Strip surrounding quotes */
384 if (outputparam[0]=='"' &&
385 memchrW(firstModifier, '~', modifierLen) != NULL) {
386 int len = strlenW(outputparam);
387 if (outputparam[len-1] == '"') {
388 outputparam[len-1]=0x00;
389 len = len - 1;
391 memmove(outputparam, &outputparam[1], (len * sizeof(WCHAR))-1);
394 /* 2. Handle the special case of a $ */
395 if (memchrW(firstModifier, '$', modifierLen) != NULL) {
396 /* Special Case: Search envar specified in $[envvar] for outputparam
397 Note both $ and : are guaranteed otherwise check above would fail */
398 WCHAR *begin = strchrW(firstModifier, '$') + 1;
399 WCHAR *end = strchrW(firstModifier, ':');
400 WCHAR env[MAX_PATH];
401 WCHAR fullpath[MAX_PATH];
403 /* Extract the env var */
404 memcpy(env, begin, (end-begin) * sizeof(WCHAR));
405 env[(end-begin)] = 0x00;
407 /* If env var not found, return empty string */
408 if ((GetEnvironmentVariableW(env, fullpath, MAX_PATH) == 0) ||
409 (SearchPathW(fullpath, outputparam, NULL, MAX_PATH, outputparam, NULL) == 0)) {
410 finaloutput[0] = 0x00;
411 outputparam[0] = 0x00;
412 skipFileParsing = TRUE;
416 /* After this, we need full information on the file,
417 which is valid not to exist. */
418 if (!skipFileParsing) {
419 if (GetFullPathNameW(outputparam, MAX_PATH, fullfilename, NULL) == 0)
420 return;
422 exists = GetFileAttributesExW(fullfilename, GetFileExInfoStandard,
423 &fileInfo);
425 /* 2. Handle 'a' : Output attributes */
426 if (exists &&
427 memchrW(firstModifier, 'a', modifierLen) != NULL) {
429 WCHAR defaults[] = {'-','-','-','-','-','-','-','-','-','\0'};
430 doneModifier = TRUE;
431 strcpyW(thisoutput, defaults);
432 if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
433 thisoutput[0]='d';
434 if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
435 thisoutput[1]='r';
436 if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE)
437 thisoutput[2]='a';
438 if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
439 thisoutput[3]='h';
440 if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)
441 thisoutput[4]='s';
442 if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_COMPRESSED)
443 thisoutput[5]='c';
444 /* FIXME: What are 6 and 7? */
445 if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
446 thisoutput[8]='l';
447 strcatW(finaloutput, thisoutput);
450 /* 3. Handle 't' : Date+time */
451 if (exists &&
452 memchrW(firstModifier, 't', modifierLen) != NULL) {
454 SYSTEMTIME systime;
455 int datelen;
457 doneModifier = TRUE;
458 if (finaloutput[0] != 0x00) strcatW(finaloutput, space);
460 /* Format the time */
461 FileTimeToSystemTime(&fileInfo.ftLastWriteTime, &systime);
462 GetDateFormatW(LOCALE_USER_DEFAULT, DATE_SHORTDATE, &systime,
463 NULL, thisoutput, MAX_PATH);
464 strcatW(thisoutput, space);
465 datelen = strlenW(thisoutput);
466 GetTimeFormatW(LOCALE_USER_DEFAULT, TIME_NOSECONDS, &systime,
467 NULL, (thisoutput+datelen), MAX_PATH-datelen);
468 strcatW(finaloutput, thisoutput);
471 /* 4. Handle 'z' : File length */
472 if (exists &&
473 memchrW(firstModifier, 'z', modifierLen) != NULL) {
474 /* FIXME: Output full 64 bit size (sprintf does not support I64 here) */
475 ULONG/*64*/ fullsize = /*(fileInfo.nFileSizeHigh << 32) +*/
476 fileInfo.nFileSizeLow;
477 static const WCHAR fmt[] = {'%','u','\0'};
479 doneModifier = TRUE;
480 if (finaloutput[0] != 0x00) strcatW(finaloutput, space);
481 wsprintfW(thisoutput, fmt, fullsize);
482 strcatW(finaloutput, thisoutput);
485 /* 4. Handle 's' : Use short paths (File doesn't have to exist) */
486 if (memchrW(firstModifier, 's', modifierLen) != NULL) {
487 if (finaloutput[0] != 0x00) strcatW(finaloutput, space);
488 /* Don't flag as doneModifier - %~s on its own is processed later */
489 GetShortPathNameW(outputparam, outputparam, sizeof(outputparam)/sizeof(outputparam[0]));
492 /* 5. Handle 'f' : Fully qualified path (File doesn't have to exist) */
493 /* Note this overrides d,p,n,x */
494 if (memchrW(firstModifier, 'f', modifierLen) != NULL) {
495 doneModifier = TRUE;
496 if (finaloutput[0] != 0x00) strcatW(finaloutput, space);
497 strcatW(finaloutput, fullfilename);
498 } else {
500 WCHAR drive[10];
501 WCHAR dir[MAX_PATH];
502 WCHAR fname[MAX_PATH];
503 WCHAR ext[MAX_PATH];
504 BOOL doneFileModifier = FALSE;
506 if (finaloutput[0] != 0x00) strcatW(finaloutput, space);
508 /* Split into components */
509 WCMD_splitpath(fullfilename, drive, dir, fname, ext);
511 /* 5. Handle 'd' : Drive Letter */
512 if (memchrW(firstModifier, 'd', modifierLen) != NULL) {
513 strcatW(finaloutput, drive);
514 doneModifier = TRUE;
515 doneFileModifier = TRUE;
518 /* 6. Handle 'p' : Path */
519 if (memchrW(firstModifier, 'p', modifierLen) != NULL) {
520 strcatW(finaloutput, dir);
521 doneModifier = TRUE;
522 doneFileModifier = TRUE;
525 /* 7. Handle 'n' : Name */
526 if (memchrW(firstModifier, 'n', modifierLen) != NULL) {
527 strcatW(finaloutput, fname);
528 doneModifier = TRUE;
529 doneFileModifier = TRUE;
532 /* 8. Handle 'x' : Ext */
533 if (memchrW(firstModifier, 'x', modifierLen) != NULL) {
534 strcatW(finaloutput, ext);
535 doneModifier = TRUE;
536 doneFileModifier = TRUE;
539 /* If 's' but no other parameter, dump the whole thing */
540 if (!doneFileModifier &&
541 memchrW(firstModifier, 's', modifierLen) != NULL) {
542 doneModifier = TRUE;
543 if (finaloutput[0] != 0x00) strcatW(finaloutput, space);
544 strcatW(finaloutput, outputparam);
549 /* If No other modifier processed, just add in parameter */
550 if (!doneModifier) strcpyW(finaloutput, outputparam);
552 /* Finish by inserting the replacement into the string */
553 WCMD_strsubstW(*start, lastModifier+1, finaloutput, -1);
556 /*******************************************************************
557 * WCMD_call - processes a batch call statement
559 * If there is a leading ':', calls within this batch program
560 * otherwise launches another program.
562 void WCMD_call (WCHAR *command) {
564 /* Run other program if no leading ':' */
565 if (*command != ':') {
566 WCMD_run_program(command, 1);
567 } else {
569 WCHAR gotoLabel[MAX_PATH];
571 strcpyW(gotoLabel, param1);
573 if (context) {
575 LARGE_INTEGER li;
577 /* Save the current file position, call the same file,
578 restore position */
579 li.QuadPart = 0;
580 li.u.LowPart = SetFilePointer(context -> h, li.u.LowPart,
581 &li.u.HighPart, FILE_CURRENT);
583 WCMD_batch (param1, command, 1, gotoLabel, context->h);
585 SetFilePointer(context -> h, li.u.LowPart,
586 &li.u.HighPart, FILE_BEGIN);
587 } else {
588 WCMD_output_asis_stderr(WCMD_LoadMessage(WCMD_CALLINSCRIPT));