dmusic: Implement IDirectMusicBufferImpl_GetMaxBytes.
[wine/multimedia.git] / programs / cmd / batch.c
blob05314f4aa04d20a45c9c43980de387313dd28321
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 /****************************************************************************
28 * WCMD_batch
30 * Open and execute a batch file.
31 * On entry *command includes the complete command line beginning with the name
32 * of the batch file (if a CALL command was entered the CALL has been removed).
33 * *file is the name of the file, which might not exist and may not have the
34 * .BAT suffix on. Called is 1 for a CALL, 0 otherwise.
36 * We need to handle recursion correctly, since one batch program might call another.
37 * So parameters for this batch file are held in a BATCH_CONTEXT structure.
39 * To support call within the same batch program, another input parameter is
40 * a label to goto once opened.
43 void WCMD_batch (WCHAR *file, WCHAR *command, BOOL called, WCHAR *startLabel, HANDLE pgmHandle)
45 HANDLE h = INVALID_HANDLE_VALUE;
46 BATCH_CONTEXT *prev_context;
48 if (startLabel == NULL) {
49 h = CreateFileW (file, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
50 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
51 if (h == INVALID_HANDLE_VALUE) {
52 SetLastError (ERROR_FILE_NOT_FOUND);
53 WCMD_print_error ();
54 return;
56 } else {
57 DuplicateHandle(GetCurrentProcess(), pgmHandle,
58 GetCurrentProcess(), &h,
59 0, FALSE, DUPLICATE_SAME_ACCESS);
63 * Create a context structure for this batch file.
66 prev_context = context;
67 context = LocalAlloc (LMEM_FIXED, sizeof (BATCH_CONTEXT));
68 context -> h = h;
69 context->batchfileW = WCMD_strdupW(file);
70 context -> command = command;
71 memset(context -> shift_count, 0x00, sizeof(context -> shift_count));
72 context -> prev_context = prev_context;
73 context -> skip_rest = FALSE;
75 /* If processing a call :label, 'goto' the label in question */
76 if (startLabel) {
77 strcpyW(param1, startLabel);
78 WCMD_goto(NULL);
82 * Work through the file line by line. Specific batch commands are processed here,
83 * the rest are handled by the main command processor.
86 while (context -> skip_rest == FALSE) {
87 CMD_LIST *toExecute = NULL; /* Commands left to be executed */
88 if (!WCMD_ReadAndParseLine(NULL, &toExecute, h))
89 break;
90 WCMD_process_commands(toExecute, FALSE, NULL, NULL);
91 WCMD_free_commands(toExecute);
92 toExecute = NULL;
94 CloseHandle (h);
97 * If invoked by a CALL, we return to the context of our caller. Otherwise return
98 * to the caller's caller.
101 HeapFree(GetProcessHeap(), 0, context->batchfileW);
102 LocalFree (context);
103 if ((prev_context != NULL) && (!called)) {
104 prev_context -> skip_rest = TRUE;
105 context = prev_context;
107 context = prev_context;
110 /*******************************************************************
111 * WCMD_parameter
113 * Extracts a delimited parameter from an input string
115 * PARAMS
116 * s [I] input string, non NULL
117 * n [I] # of the (possibly double quotes-delimited) parameter to return
118 * Starts at 0
119 * start [O] if non NULL, pointer to the start of the nth parameter in s,
120 * potentially a " character
121 * end [O] if non NULL, pointer to the last char of
122 * the nth parameter in s, potentially a " character
124 * RETURNS
125 * Success: Returns the nth delimited parameter found in s.
126 * *start points to the start of the param, possibly a starting
127 * double quotes character
128 * Failure: Returns an empty string if the param is not found.
129 * *start is set to NULL
131 * NOTES
132 * Return value is stored in static storage, hence is overwritten
133 * after each call.
134 * Doesn't include any potentially delimiting double quotes
136 WCHAR *WCMD_parameter (WCHAR *s, int n, WCHAR **start, WCHAR **end) {
137 int curParamNb = 0;
138 static WCHAR param[MAX_PATH];
139 WCHAR *p = s, *q;
140 BOOL quotesDelimited;
142 if (start != NULL) *start = NULL;
143 if (end != NULL) *end = NULL;
144 param[0] = '\0';
145 while (TRUE) {
146 while (*p && ((*p == ' ') || (*p == ',') || (*p == '=') || (*p == '\t')))
147 p++;
148 if (*p == '\0') return param;
150 quotesDelimited = (*p == '"');
151 if (start != NULL && curParamNb == n) *start = p;
153 if (quotesDelimited) {
154 q = ++p;
155 while (*p && *p != '"') p++;
156 } else {
157 q = p;
158 while (*p && (*p != ' ') && (*p != ',') && (*p != '=') && (*p != '\t'))
159 p++;
161 if (curParamNb == n) {
162 memcpy(param, q, (p - q) * sizeof(WCHAR));
163 param[p-q] = '\0';
164 if (end) *end = p - 1 + quotesDelimited;
165 return param;
167 if (quotesDelimited && *p == '"') p++;
168 curParamNb++;
172 /****************************************************************************
173 * WCMD_fgets
175 * Gets one line from a file/console and puts it into buffer buf
176 * Pre: buf has size noChars
177 * 1 <= noChars <= MAXSTRING
178 * Post: buf is filled with at most noChars-1 characters, and gets nul-terminated
179 buf does not include EOL terminator
180 * Returns:
181 * buf on success
182 * NULL on error or EOF
185 WCHAR *WCMD_fgets(WCHAR *buf, DWORD noChars, HANDLE h)
187 DWORD charsRead;
188 BOOL status;
189 LARGE_INTEGER filepos;
190 DWORD i;
192 /* We can't use the native f* functions because of the filename syntax differences
193 between DOS and Unix. Also need to lose the LF (or CRLF) from the line. */
195 if (!WCMD_is_console_handle(h)) {
196 /* Save current file position */
197 filepos.QuadPart = 0;
198 SetFilePointerEx(h, filepos, &filepos, FILE_CURRENT);
201 status = WCMD_ReadFile(h, buf, noChars, &charsRead);
202 if (!status || charsRead == 0) return NULL;
204 /* Find first EOL */
205 for (i = 0; i < charsRead; i++) {
206 if (buf[i] == '\n' || buf[i] == '\r')
207 break;
210 if (!WCMD_is_console_handle(h) && i != charsRead) {
211 /* Sets file pointer to the start of the next line, if any */
212 filepos.QuadPart += i + 1 + (buf[i] == '\r' ? 1 : 0);
213 SetFilePointerEx(h, filepos, NULL, FILE_BEGIN);
216 /* Truncate at EOL (or end of buffer) */
217 if (i == noChars)
218 i--;
220 buf[i] = '\0';
222 return buf;
225 /* WCMD_splitpath - copied from winefile as no obvious way to use it otherwise */
226 void WCMD_splitpath(const WCHAR* path, WCHAR* drv, WCHAR* dir, WCHAR* name, WCHAR* ext)
228 const WCHAR* end; /* end of processed string */
229 const WCHAR* p; /* search pointer */
230 const WCHAR* s; /* copy pointer */
232 /* extract drive name */
233 if (path[0] && path[1]==':') {
234 if (drv) {
235 *drv++ = *path++;
236 *drv++ = *path++;
237 *drv = '\0';
239 } else if (drv)
240 *drv = '\0';
242 end = path + strlenW(path);
244 /* search for begin of file extension */
245 for(p=end; p>path && *--p!='\\' && *p!='/'; )
246 if (*p == '.') {
247 end = p;
248 break;
251 if (ext)
252 for(s=end; (*ext=*s++); )
253 ext++;
255 /* search for end of directory name */
256 for(p=end; p>path; )
257 if (*--p=='\\' || *p=='/') {
258 p++;
259 break;
262 if (name) {
263 for(s=p; s<end; )
264 *name++ = *s++;
266 *name = '\0';
269 if (dir) {
270 for(s=path; s<p; )
271 *dir++ = *s++;
273 *dir = '\0';
277 /****************************************************************************
278 * WCMD_HandleTildaModifiers
280 * Handle the ~ modifiers when expanding %0-9 or (%a-z in for command)
281 * %~xxxxxV (V=0-9 or A-Z)
282 * Where xxxx is any combination of:
283 * ~ - Removes quotes
284 * f - Fully qualified path (assumes current dir if not drive\dir)
285 * d - drive letter
286 * p - path
287 * n - filename
288 * x - file extension
289 * s - path with shortnames
290 * a - attributes
291 * t - date/time
292 * z - size
293 * $ENVVAR: - Searches ENVVAR for (contents of V) and expands to fully
294 * qualified path
296 * To work out the length of the modifier:
298 * Note: In the case of %0-9 knowing the end of the modifier is easy,
299 * but in a for loop, the for end WCHARacter may also be a modifier
300 * eg. for %a in (c:\a.a) do echo XXX
301 * where XXX = %~a (just ~)
302 * %~aa (~ and attributes)
303 * %~aaxa (~, attributes and extension)
304 * BUT %~aax (~ and attributes followed by 'x')
306 * Hence search forwards until find an invalid modifier, and then
307 * backwards until find for variable or 0-9
309 void WCMD_HandleTildaModifiers(WCHAR **start, const WCHAR *forVariable,
310 const WCHAR *forValue, BOOL justFors) {
312 #define NUMMODIFIERS 11
313 static const WCHAR validmodifiers[NUMMODIFIERS] = {
314 '~', 'f', 'd', 'p', 'n', 'x', 's', 'a', 't', 'z', '$'
317 WIN32_FILE_ATTRIBUTE_DATA fileInfo;
318 WCHAR outputparam[MAX_PATH];
319 WCHAR finaloutput[MAX_PATH];
320 WCHAR fullfilename[MAX_PATH];
321 WCHAR thisoutput[MAX_PATH];
322 WCHAR *pos = *start+1;
323 WCHAR *firstModifier = pos;
324 WCHAR *lastModifier = NULL;
325 int modifierLen = 0;
326 BOOL finished = FALSE;
327 int i = 0;
328 BOOL exists = TRUE;
329 BOOL skipFileParsing = FALSE;
330 BOOL doneModifier = FALSE;
332 /* Search forwards until find invalid character modifier */
333 while (!finished) {
335 /* Work on the previous character */
336 if (lastModifier != NULL) {
338 for (i=0; i<NUMMODIFIERS; i++) {
339 if (validmodifiers[i] == *lastModifier) {
341 /* Special case '$' to skip until : found */
342 if (*lastModifier == '$') {
343 while (*pos != ':' && *pos) pos++;
344 if (*pos == 0x00) return; /* Invalid syntax */
345 pos++; /* Skip ':' */
347 break;
351 if (i==NUMMODIFIERS) {
352 finished = TRUE;
356 /* Save this one away */
357 if (!finished) {
358 lastModifier = pos;
359 pos++;
363 while (lastModifier > firstModifier) {
364 WINE_TRACE("Looking backwards for parameter id: %s / %s\n",
365 wine_dbgstr_w(lastModifier), wine_dbgstr_w(forVariable));
367 if (!justFors && context && (*lastModifier >= '0' && *lastModifier <= '9')) {
368 /* Its a valid parameter identifier - OK */
369 break;
371 } else if (forVariable && *lastModifier == *(forVariable+1)) {
372 /* Its a valid parameter identifier - OK */
373 break;
375 } else {
376 lastModifier--;
379 if (lastModifier == firstModifier) return; /* Invalid syntax */
381 /* Extract the parameter to play with */
382 if (*lastModifier == '0') {
383 strcpyW(outputparam, context->batchfileW);
384 } else if ((*lastModifier >= '1' && *lastModifier <= '9')) {
385 strcpyW(outputparam,
386 WCMD_parameter (context -> command, *lastModifier-'0' + context -> shift_count[*lastModifier-'0'],
387 NULL, NULL));
388 } else {
389 strcpyW(outputparam, forValue);
392 /* So now, firstModifier points to beginning of modifiers, lastModifier
393 points to the variable just after the modifiers. Process modifiers
394 in a specific order, remembering there could be duplicates */
395 modifierLen = lastModifier - firstModifier;
396 finaloutput[0] = 0x00;
398 /* Useful for debugging purposes: */
399 /*printf("Modifier string '%*.*s' and variable is %c\n Param starts as '%s'\n",
400 (modifierLen), (modifierLen), firstModifier, *lastModifier,
401 outputparam);*/
403 /* 1. Handle '~' : Strip surrounding quotes */
404 if (outputparam[0]=='"' &&
405 memchrW(firstModifier, '~', modifierLen) != NULL) {
406 int len = strlenW(outputparam);
407 if (outputparam[len-1] == '"') {
408 outputparam[len-1]=0x00;
409 len = len - 1;
411 memmove(outputparam, &outputparam[1], (len * sizeof(WCHAR))-1);
414 /* 2. Handle the special case of a $ */
415 if (memchrW(firstModifier, '$', modifierLen) != NULL) {
416 /* Special Case: Search envar specified in $[envvar] for outputparam
417 Note both $ and : are guaranteed otherwise check above would fail */
418 WCHAR *begin = strchrW(firstModifier, '$') + 1;
419 WCHAR *end = strchrW(firstModifier, ':');
420 WCHAR env[MAX_PATH];
421 WCHAR fullpath[MAX_PATH];
423 /* Extract the env var */
424 memcpy(env, begin, (end-begin) * sizeof(WCHAR));
425 env[(end-begin)] = 0x00;
427 /* If env var not found, return empty string */
428 if ((GetEnvironmentVariableW(env, fullpath, MAX_PATH) == 0) ||
429 (SearchPathW(fullpath, outputparam, NULL, MAX_PATH, outputparam, NULL) == 0)) {
430 finaloutput[0] = 0x00;
431 outputparam[0] = 0x00;
432 skipFileParsing = TRUE;
436 /* After this, we need full information on the file,
437 which is valid not to exist. */
438 if (!skipFileParsing) {
439 if (GetFullPathNameW(outputparam, MAX_PATH, fullfilename, NULL) == 0)
440 return;
442 exists = GetFileAttributesExW(fullfilename, GetFileExInfoStandard,
443 &fileInfo);
445 /* 2. Handle 'a' : Output attributes */
446 if (exists &&
447 memchrW(firstModifier, 'a', modifierLen) != NULL) {
449 WCHAR defaults[] = {'-','-','-','-','-','-','-','-','-','\0'};
450 doneModifier = TRUE;
451 strcpyW(thisoutput, defaults);
452 if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
453 thisoutput[0]='d';
454 if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_READONLY)
455 thisoutput[1]='r';
456 if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE)
457 thisoutput[2]='a';
458 if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)
459 thisoutput[3]='h';
460 if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)
461 thisoutput[4]='s';
462 if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_COMPRESSED)
463 thisoutput[5]='c';
464 /* FIXME: What are 6 and 7? */
465 if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
466 thisoutput[8]='l';
467 strcatW(finaloutput, thisoutput);
470 /* 3. Handle 't' : Date+time */
471 if (exists &&
472 memchrW(firstModifier, 't', modifierLen) != NULL) {
474 SYSTEMTIME systime;
475 int datelen;
477 doneModifier = TRUE;
478 if (finaloutput[0] != 0x00) strcatW(finaloutput, spaceW);
480 /* Format the time */
481 FileTimeToSystemTime(&fileInfo.ftLastWriteTime, &systime);
482 GetDateFormatW(LOCALE_USER_DEFAULT, DATE_SHORTDATE, &systime,
483 NULL, thisoutput, MAX_PATH);
484 strcatW(thisoutput, spaceW);
485 datelen = strlenW(thisoutput);
486 GetTimeFormatW(LOCALE_USER_DEFAULT, TIME_NOSECONDS, &systime,
487 NULL, (thisoutput+datelen), MAX_PATH-datelen);
488 strcatW(finaloutput, thisoutput);
491 /* 4. Handle 'z' : File length */
492 if (exists &&
493 memchrW(firstModifier, 'z', modifierLen) != NULL) {
494 /* FIXME: Output full 64 bit size (sprintf does not support I64 here) */
495 ULONG/*64*/ fullsize = /*(fileInfo.nFileSizeHigh << 32) +*/
496 fileInfo.nFileSizeLow;
497 static const WCHAR fmt[] = {'%','u','\0'};
499 doneModifier = TRUE;
500 if (finaloutput[0] != 0x00) strcatW(finaloutput, spaceW);
501 wsprintfW(thisoutput, fmt, fullsize);
502 strcatW(finaloutput, thisoutput);
505 /* 4. Handle 's' : Use short paths (File doesn't have to exist) */
506 if (memchrW(firstModifier, 's', modifierLen) != NULL) {
507 if (finaloutput[0] != 0x00) strcatW(finaloutput, spaceW);
508 /* Don't flag as doneModifier - %~s on its own is processed later */
509 GetShortPathNameW(outputparam, outputparam, sizeof(outputparam)/sizeof(outputparam[0]));
512 /* 5. Handle 'f' : Fully qualified path (File doesn't have to exist) */
513 /* Note this overrides d,p,n,x */
514 if (memchrW(firstModifier, 'f', modifierLen) != NULL) {
515 doneModifier = TRUE;
516 if (finaloutput[0] != 0x00) strcatW(finaloutput, spaceW);
517 strcatW(finaloutput, fullfilename);
518 } else {
520 WCHAR drive[10];
521 WCHAR dir[MAX_PATH];
522 WCHAR fname[MAX_PATH];
523 WCHAR ext[MAX_PATH];
524 BOOL doneFileModifier = FALSE;
526 if (finaloutput[0] != 0x00) strcatW(finaloutput, spaceW);
528 /* Split into components */
529 WCMD_splitpath(fullfilename, drive, dir, fname, ext);
531 /* 5. Handle 'd' : Drive Letter */
532 if (memchrW(firstModifier, 'd', modifierLen) != NULL) {
533 strcatW(finaloutput, drive);
534 doneModifier = TRUE;
535 doneFileModifier = TRUE;
538 /* 6. Handle 'p' : Path */
539 if (memchrW(firstModifier, 'p', modifierLen) != NULL) {
540 strcatW(finaloutput, dir);
541 doneModifier = TRUE;
542 doneFileModifier = TRUE;
545 /* 7. Handle 'n' : Name */
546 if (memchrW(firstModifier, 'n', modifierLen) != NULL) {
547 strcatW(finaloutput, fname);
548 doneModifier = TRUE;
549 doneFileModifier = TRUE;
552 /* 8. Handle 'x' : Ext */
553 if (memchrW(firstModifier, 'x', modifierLen) != NULL) {
554 strcatW(finaloutput, ext);
555 doneModifier = TRUE;
556 doneFileModifier = TRUE;
559 /* If 's' but no other parameter, dump the whole thing */
560 if (!doneFileModifier &&
561 memchrW(firstModifier, 's', modifierLen) != NULL) {
562 doneModifier = TRUE;
563 if (finaloutput[0] != 0x00) strcatW(finaloutput, spaceW);
564 strcatW(finaloutput, outputparam);
569 /* If No other modifier processed, just add in parameter */
570 if (!doneModifier) strcpyW(finaloutput, outputparam);
572 /* Finish by inserting the replacement into the string */
573 WCMD_strsubstW(*start, lastModifier+1, finaloutput, -1);
576 /*******************************************************************
577 * WCMD_call - processes a batch call statement
579 * If there is a leading ':', calls within this batch program
580 * otherwise launches another program.
582 void WCMD_call (WCHAR *command) {
584 /* Run other program if no leading ':' */
585 if (*command != ':') {
586 WCMD_run_program(command, TRUE);
587 } else {
589 WCHAR gotoLabel[MAX_PATH];
591 strcpyW(gotoLabel, param1);
593 if (context) {
595 LARGE_INTEGER li;
597 /* Save the current file position, call the same file,
598 restore position */
599 li.QuadPart = 0;
600 li.u.LowPart = SetFilePointer(context -> h, li.u.LowPart,
601 &li.u.HighPart, FILE_CURRENT);
603 WCMD_batch (param1, command, TRUE, gotoLabel, context->h);
605 SetFilePointer(context -> h, li.u.LowPart,
606 &li.u.HighPart, FILE_BEGIN);
607 } else {
608 WCMD_output_asis_stderr(WCMD_LoadMessage(WCMD_CALLINSCRIPT));