cmd.exe: Fix running programs from root of drive.
[wine/multimedia.git] / programs / cmd / wcmdmain.c
blob36faa8b9141678fe92d6d643cda8928d666495c0
1 /*
2 * CMD - Wine-compatible command line interface.
4 * Copyright (C) 1999 - 2001 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 * FIXME:
24 * - Cannot handle parameters in quotes
25 * - Lots of functionality missing from builtins
28 #include "config.h"
29 #include <time.h>
30 #include "wcmd.h"
31 #include "wine/debug.h"
33 WINE_DEFAULT_DEBUG_CHANNEL(cmd);
35 const WCHAR inbuilt[][10] = {
36 {'A','T','T','R','I','B','\0'},
37 {'C','A','L','L','\0'},
38 {'C','D','\0'},
39 {'C','H','D','I','R','\0'},
40 {'C','L','S','\0'},
41 {'C','O','P','Y','\0'},
42 {'C','T','T','Y','\0'},
43 {'D','A','T','E','\0'},
44 {'D','E','L','\0'},
45 {'D','I','R','\0'},
46 {'E','C','H','O','\0'},
47 {'E','R','A','S','E','\0'},
48 {'F','O','R','\0'},
49 {'G','O','T','O','\0'},
50 {'H','E','L','P','\0'},
51 {'I','F','\0'},
52 {'L','A','B','E','L','\0'},
53 {'M','D','\0'},
54 {'M','K','D','I','R','\0'},
55 {'M','O','V','E','\0'},
56 {'P','A','T','H','\0'},
57 {'P','A','U','S','E','\0'},
58 {'P','R','O','M','P','T','\0'},
59 {'R','E','M','\0'},
60 {'R','E','N','\0'},
61 {'R','E','N','A','M','E','\0'},
62 {'R','D','\0'},
63 {'R','M','D','I','R','\0'},
64 {'S','E','T','\0'},
65 {'S','H','I','F','T','\0'},
66 {'T','I','M','E','\0'},
67 {'T','I','T','L','E','\0'},
68 {'T','Y','P','E','\0'},
69 {'V','E','R','I','F','Y','\0'},
70 {'V','E','R','\0'},
71 {'V','O','L','\0'},
72 {'E','N','D','L','O','C','A','L','\0'},
73 {'S','E','T','L','O','C','A','L','\0'},
74 {'P','U','S','H','D','\0'},
75 {'P','O','P','D','\0'},
76 {'A','S','S','O','C','\0'},
77 {'C','O','L','O','R','\0'},
78 {'F','T','Y','P','E','\0'},
79 {'M','O','R','E','\0'},
80 {'E','X','I','T','\0'}
83 HINSTANCE hinst;
84 DWORD errorlevel;
85 int echo_mode = 1, verify_mode = 0, defaultColor = 7;
86 static int opt_c, opt_k, opt_s;
87 const WCHAR newline[] = {'\n','\0'};
88 static const WCHAR equalsW[] = {'=','\0'};
89 static const WCHAR closeBW[] = {')','\0'};
90 WCHAR anykey[100];
91 WCHAR version_string[100];
92 WCHAR quals[MAX_PATH], param1[MAX_PATH], param2[MAX_PATH];
93 BATCH_CONTEXT *context = NULL;
94 extern struct env_stack *pushd_directories;
95 static const WCHAR *pagedMessage = NULL;
96 static char *output_bufA = NULL;
97 #define MAX_WRITECONSOLE_SIZE 65535
98 BOOL unicodePipes = FALSE;
100 static WCHAR *WCMD_expand_envvar(WCHAR *start, WCHAR *forvar, WCHAR *forVal);
101 static void WCMD_output_asis_len(const WCHAR *message, int len, HANDLE device);
103 /*****************************************************************************
104 * Main entry point. This is a console application so we have a main() not a
105 * winmain().
108 int wmain (int argc, WCHAR *argvW[])
110 int args;
111 WCHAR *cmd = NULL;
112 WCHAR string[1024];
113 WCHAR envvar[4];
114 HANDLE h;
115 int opt_q;
116 int opt_t = 0;
117 static const WCHAR autoexec[] = {'\\','a','u','t','o','e','x','e','c','.',
118 'b','a','t','\0'};
119 char ansiVersion[100];
120 CMD_LIST *toExecute = NULL; /* Commands left to be executed */
122 srand(time(NULL));
124 /* Pre initialize some messages */
125 strcpy(ansiVersion, PACKAGE_VERSION);
126 MultiByteToWideChar(CP_ACP, 0, ansiVersion, -1, string, 1024);
127 wsprintf(version_string, WCMD_LoadMessage(WCMD_VERSION), string);
128 strcpyW(anykey, WCMD_LoadMessage(WCMD_ANYKEY));
130 args = argc;
131 opt_c=opt_k=opt_q=opt_s=0;
132 while (args > 0)
134 WCHAR c;
135 WINE_TRACE("Command line parm: '%s'\n", wine_dbgstr_w(*argvW));
136 if ((*argvW)[0]!='/' || (*argvW)[1]=='\0') {
137 argvW++;
138 args--;
139 continue;
142 c=(*argvW)[1];
143 if (tolowerW(c)=='c') {
144 opt_c=1;
145 } else if (tolowerW(c)=='q') {
146 opt_q=1;
147 } else if (tolowerW(c)=='k') {
148 opt_k=1;
149 } else if (tolowerW(c)=='s') {
150 opt_s=1;
151 } else if (tolowerW(c)=='a') {
152 unicodePipes=FALSE;
153 } else if (tolowerW(c)=='u') {
154 unicodePipes=TRUE;
155 } else if (tolowerW(c)=='t' && (*argvW)[2]==':') {
156 opt_t=strtoulW(&(*argvW)[3], NULL, 16);
157 } else if (tolowerW(c)=='x' || tolowerW(c)=='y') {
158 /* Ignored for compatibility with Windows */
161 if ((*argvW)[2]==0) {
162 argvW++;
163 args--;
165 else /* handle `cmd /cnotepad.exe` and `cmd /x/c ...` */
167 *argvW+=2;
170 if (opt_c || opt_k) /* break out of parsing immediately after c or k */
171 break;
174 if (opt_q) {
175 const WCHAR eoff[] = {'O','F','F','\0'};
176 WCMD_echo(eoff);
179 if (opt_c || opt_k) {
180 int len,qcount;
181 WCHAR** arg;
182 int argsLeft;
183 WCHAR* p;
185 /* opt_s left unflagged if the command starts with and contains exactly
186 * one quoted string (exactly two quote characters). The quoted string
187 * must be an executable name that has whitespace and must not have the
188 * following characters: &<>()@^| */
190 /* Build the command to execute */
191 len = 0;
192 qcount = 0;
193 argsLeft = args;
194 for (arg = argvW; argsLeft>0; arg++,argsLeft--)
196 int has_space,bcount;
197 WCHAR* a;
199 has_space=0;
200 bcount=0;
201 a=*arg;
202 if( !*a ) has_space=1;
203 while (*a!='\0') {
204 if (*a=='\\') {
205 bcount++;
206 } else {
207 if (*a==' ' || *a=='\t') {
208 has_space=1;
209 } else if (*a=='"') {
210 /* doubling of '\' preceding a '"',
211 * plus escaping of said '"'
213 len+=2*bcount+1;
214 qcount++;
216 bcount=0;
218 a++;
220 len+=(a-*arg) + 1; /* for the separating space */
221 if (has_space)
223 len+=2; /* for the quotes */
224 qcount+=2;
228 if (qcount!=2)
229 opt_s=1;
231 /* check argvW[0] for a space and invalid characters */
232 if (!opt_s) {
233 opt_s=1;
234 p=*argvW;
235 while (*p!='\0') {
236 if (*p=='&' || *p=='<' || *p=='>' || *p=='(' || *p==')'
237 || *p=='@' || *p=='^' || *p=='|') {
238 opt_s=1;
239 break;
241 if (*p==' ')
242 opt_s=0;
243 p++;
247 cmd = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
248 if (!cmd)
249 exit(1);
251 p = cmd;
252 argsLeft = args;
253 for (arg = argvW; argsLeft>0; arg++,argsLeft--)
255 int has_space,has_quote;
256 WCHAR* a;
258 /* Check for quotes and spaces in this argument */
259 has_space=has_quote=0;
260 a=*arg;
261 if( !*a ) has_space=1;
262 while (*a!='\0') {
263 if (*a==' ' || *a=='\t') {
264 has_space=1;
265 if (has_quote)
266 break;
267 } else if (*a=='"') {
268 has_quote=1;
269 if (has_space)
270 break;
272 a++;
275 /* Now transfer it to the command line */
276 if (has_space)
277 *p++='"';
278 if (has_quote) {
279 int bcount;
280 WCHAR* a;
282 bcount=0;
283 a=*arg;
284 while (*a!='\0') {
285 if (*a=='\\') {
286 *p++=*a;
287 bcount++;
288 } else {
289 if (*a=='"') {
290 int i;
292 /* Double all the '\\' preceding this '"', plus one */
293 for (i=0;i<=bcount;i++)
294 *p++='\\';
295 *p++='"';
296 } else {
297 *p++=*a;
299 bcount=0;
301 a++;
303 } else {
304 strcpyW(p,*arg);
305 p+=strlenW(*arg);
307 if (has_space)
308 *p++='"';
309 *p++=' ';
311 if (p > cmd)
312 p--; /* remove last space */
313 *p = '\0';
315 WINE_TRACE("/c command line: '%s'\n", wine_dbgstr_w(cmd));
317 /* strip first and last quote characters if opt_s; check for invalid
318 * executable is done later */
319 if (opt_s && *cmd=='\"')
320 WCMD_opt_s_strip_quotes(cmd);
323 if (opt_c) {
324 /* If we do a "wcmd /c command", we don't want to allocate a new
325 * console since the command returns immediately. Rather, we use
326 * the currently allocated input and output handles. This allows
327 * us to pipe to and read from the command interpreter.
330 /* Parse the command string, without reading any more input */
331 WCMD_ReadAndParseLine(cmd, &toExecute, INVALID_HANDLE_VALUE);
332 WCMD_process_commands(toExecute, FALSE, NULL, NULL);
333 WCMD_free_commands(toExecute);
334 toExecute = NULL;
336 HeapFree(GetProcessHeap(), 0, cmd);
337 return errorlevel;
340 SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), ENABLE_LINE_INPUT |
341 ENABLE_ECHO_INPUT | ENABLE_PROCESSED_INPUT);
342 SetConsoleTitle(WCMD_LoadMessage(WCMD_CONSTITLE));
344 /* Note: cmd.exe /c dir does not get a new color, /k dir does */
345 if (opt_t) {
346 if (!(((opt_t & 0xF0) >> 4) == (opt_t & 0x0F))) {
347 defaultColor = opt_t & 0xFF;
348 param1[0] = 0x00;
349 WCMD_color();
351 } else {
352 /* Check HKCU\Software\Microsoft\Command Processor
353 Then HKLM\Software\Microsoft\Command Processor
354 for defaultcolour value
355 Note Can be supplied as DWORD or REG_SZ
356 Note2 When supplied as REG_SZ it's in decimal!!! */
357 HKEY key;
358 DWORD type;
359 DWORD value=0, size=4;
360 static const WCHAR regKeyW[] = {'S','o','f','t','w','a','r','e','\\',
361 'M','i','c','r','o','s','o','f','t','\\',
362 'C','o','m','m','a','n','d',' ','P','r','o','c','e','s','s','o','r','\0'};
363 static const WCHAR dfltColorW[] = {'D','e','f','a','u','l','t','C','o','l','o','r','\0'};
365 if (RegOpenKeyEx(HKEY_CURRENT_USER, regKeyW,
366 0, KEY_READ, &key) == ERROR_SUCCESS) {
367 WCHAR strvalue[4];
369 /* See if DWORD or REG_SZ */
370 if (RegQueryValueEx(key, dfltColorW, NULL, &type,
371 NULL, NULL) == ERROR_SUCCESS) {
372 if (type == REG_DWORD) {
373 size = sizeof(DWORD);
374 RegQueryValueEx(key, dfltColorW, NULL, NULL,
375 (LPBYTE)&value, &size);
376 } else if (type == REG_SZ) {
377 size = sizeof(strvalue)/sizeof(WCHAR);
378 RegQueryValueEx(key, dfltColorW, NULL, NULL,
379 (LPBYTE)strvalue, &size);
380 value = strtoulW(strvalue, NULL, 10);
383 RegCloseKey(key);
386 if (value == 0 && RegOpenKeyEx(HKEY_LOCAL_MACHINE, regKeyW,
387 0, KEY_READ, &key) == ERROR_SUCCESS) {
388 WCHAR strvalue[4];
390 /* See if DWORD or REG_SZ */
391 if (RegQueryValueEx(key, dfltColorW, NULL, &type,
392 NULL, NULL) == ERROR_SUCCESS) {
393 if (type == REG_DWORD) {
394 size = sizeof(DWORD);
395 RegQueryValueEx(key, dfltColorW, NULL, NULL,
396 (LPBYTE)&value, &size);
397 } else if (type == REG_SZ) {
398 size = sizeof(strvalue)/sizeof(WCHAR);
399 RegQueryValueEx(key, dfltColorW, NULL, NULL,
400 (LPBYTE)strvalue, &size);
401 value = strtoulW(strvalue, NULL, 10);
404 RegCloseKey(key);
407 /* If one found, set the screen to that colour */
408 if (!(((value & 0xF0) >> 4) == (value & 0x0F))) {
409 defaultColor = value & 0xFF;
410 param1[0] = 0x00;
411 WCMD_color();
416 /* Save cwd into appropriate env var */
417 GetCurrentDirectory(1024, string);
418 if (IsCharAlpha(string[0]) && string[1] == ':') {
419 static const WCHAR fmt[] = {'=','%','c',':','\0'};
420 wsprintf(envvar, fmt, string[0]);
421 SetEnvironmentVariable(envvar, string);
424 if (opt_k) {
425 /* Parse the command string, without reading any more input */
426 WCMD_ReadAndParseLine(cmd, &toExecute, INVALID_HANDLE_VALUE);
427 WCMD_process_commands(toExecute, FALSE, NULL, NULL);
428 WCMD_free_commands(toExecute);
429 toExecute = NULL;
430 HeapFree(GetProcessHeap(), 0, cmd);
434 * If there is an AUTOEXEC.BAT file, try to execute it.
437 GetFullPathName (autoexec, sizeof(string)/sizeof(WCHAR), string, NULL);
438 h = CreateFile (string, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
439 if (h != INVALID_HANDLE_VALUE) {
440 CloseHandle (h);
441 #if 0
442 WCMD_batch (autoexec, autoexec, 0, NULL, INVALID_HANDLE_VALUE);
443 #endif
447 * Loop forever getting commands and executing them.
450 WCMD_version ();
451 while (TRUE) {
453 /* Read until EOF (which for std input is never, but if redirect
454 in place, may occur */
455 WCMD_show_prompt ();
456 if (WCMD_ReadAndParseLine(NULL, &toExecute,
457 GetStdHandle(STD_INPUT_HANDLE)) == NULL)
458 break;
459 WCMD_process_commands(toExecute, FALSE, NULL, NULL);
460 WCMD_free_commands(toExecute);
461 toExecute = NULL;
463 return 0;
466 /*****************************************************************************
467 * Expand the command. Native expands lines from batch programs as they are
468 * read in and not again, except for 'for' variable substitution.
469 * eg. As evidence, "echo %1 && shift && echo %1" or "echo %%path%%"
471 void handleExpansion(WCHAR *cmd, BOOL justFors, WCHAR *forVariable, WCHAR *forValue) {
473 /* For commands in a context (batch program): */
474 /* Expand environment variables in a batch file %{0-9} first */
475 /* including support for any ~ modifiers */
476 /* Additionally: */
477 /* Expand the DATE, TIME, CD, RANDOM and ERRORLEVEL special */
478 /* names allowing environment variable overrides */
479 /* NOTE: To support the %PATH:xxx% syntax, also perform */
480 /* manual expansion of environment variables here */
482 WCHAR *p = cmd;
483 WCHAR *s, *t;
484 int i;
486 while ((p = strchrW(p, '%'))) {
488 WINE_TRACE("Translate command:%s %d (at: %s)\n",
489 wine_dbgstr_w(cmd), justFors, wine_dbgstr_w(p));
490 i = *(p+1) - '0';
492 /* Don't touch %% unless its in Batch */
493 if (!justFors && *(p+1) == '%') {
494 if (context) {
495 s = WCMD_strdupW(p+1);
496 strcpyW (p, s);
497 free (s);
499 p+=1;
501 /* Replace %~ modifications if in batch program */
502 } else if (*(p+1) == '~') {
503 WCMD_HandleTildaModifiers(&p, forVariable, forValue, justFors);
504 p++;
506 /* Replace use of %0...%9 if in batch program*/
507 } else if (!justFors && context && (i >= 0) && (i <= 9)) {
508 s = WCMD_strdupW(p+2);
509 t = WCMD_parameter (context -> command, i + context -> shift_count[i], NULL);
510 strcpyW (p, t);
511 strcatW (p, s);
512 free (s);
514 /* Replace use of %* if in batch program*/
515 } else if (!justFors && context && *(p+1)=='*') {
516 WCHAR *startOfParms = NULL;
517 s = WCMD_strdupW(p+2);
518 t = WCMD_parameter (context -> command, 1, &startOfParms);
519 if (startOfParms != NULL) strcpyW (p, startOfParms);
520 else *p = 0x00;
521 strcatW (p, s);
522 free (s);
524 } else if (forVariable &&
525 (CompareString (LOCALE_USER_DEFAULT,
526 SORT_STRINGSORT,
528 strlenW(forVariable),
529 forVariable, -1) == 2)) {
530 s = WCMD_strdupW(p + strlenW(forVariable));
531 strcpyW(p, forValue);
532 strcatW(p, s);
533 free(s);
535 } else if (!justFors) {
536 p = WCMD_expand_envvar(p, forVariable, forValue);
538 /* In a FOR loop, see if this is the variable to replace */
539 } else { /* Ignore %'s on second pass of batch program */
540 p++;
544 return;
548 /*****************************************************************************
549 * Process one command. If the command is EXIT this routine does not return.
550 * We will recurse through here executing batch files.
554 void WCMD_execute (WCHAR *command, WCHAR *redirects,
555 WCHAR *forVariable, WCHAR *forValue,
556 CMD_LIST **cmdList)
558 WCHAR *cmd, *p, *redir;
559 int status, i;
560 DWORD count, creationDisposition;
561 HANDLE h;
562 WCHAR *whichcmd;
563 SECURITY_ATTRIBUTES sa;
564 WCHAR *new_cmd;
565 HANDLE old_stdhandles[3] = {INVALID_HANDLE_VALUE,
566 INVALID_HANDLE_VALUE,
567 INVALID_HANDLE_VALUE};
568 DWORD idx_stdhandles[3] = {STD_INPUT_HANDLE,
569 STD_OUTPUT_HANDLE,
570 STD_ERROR_HANDLE};
572 WINE_TRACE("command on entry:%s (%p), with '%s'='%s'\n",
573 wine_dbgstr_w(command), cmdList,
574 wine_dbgstr_w(forVariable), wine_dbgstr_w(forValue));
576 /* Move copy of the command onto the heap so it can be expanded */
577 new_cmd = HeapAlloc( GetProcessHeap(), 0, MAXSTRING * sizeof(WCHAR));
578 strcpyW(new_cmd, command);
580 /* Expand variables in command line mode only (batch mode will
581 be expanded as the line is read in, except for 'for' loops) */
582 handleExpansion(new_cmd, (context != NULL), forVariable, forValue);
583 cmd = new_cmd;
585 /* Show prompt before batch line IF echo is on and in batch program */
586 if (context && echo_mode && (cmd[0] != '@')) {
587 WCMD_show_prompt();
588 WCMD_output_asis ( cmd);
589 WCMD_output_asis ( newline);
593 * Changing default drive has to be handled as a special case.
596 if ((cmd[1] == ':') && IsCharAlpha (cmd[0]) && (strlenW(cmd) == 2)) {
597 WCHAR envvar[5];
598 WCHAR dir[MAX_PATH];
600 /* According to MSDN CreateProcess docs, special env vars record
601 the current directory on each drive, in the form =C:
602 so see if one specified, and if so go back to it */
603 strcpyW(envvar, equalsW);
604 strcatW(envvar, cmd);
605 if (GetEnvironmentVariable(envvar, dir, MAX_PATH) == 0) {
606 static const WCHAR fmt[] = {'%','s','\\','\0'};
607 wsprintf(cmd, fmt, cmd);
609 status = SetCurrentDirectory (cmd);
610 if (!status) WCMD_print_error ();
611 HeapFree( GetProcessHeap(), 0, cmd );
612 return;
615 sa.nLength = sizeof(sa);
616 sa.lpSecurityDescriptor = NULL;
617 sa.bInheritHandle = TRUE;
620 * Redirect stdin, stdout and/or stderr if required.
623 if ((p = strchrW(redirects,'<')) != NULL) {
624 h = CreateFile (WCMD_parameter (++p, 0, NULL), GENERIC_READ, FILE_SHARE_READ, &sa, OPEN_EXISTING,
625 FILE_ATTRIBUTE_NORMAL, NULL);
626 if (h == INVALID_HANDLE_VALUE) {
627 WCMD_print_error ();
628 HeapFree( GetProcessHeap(), 0, cmd );
629 return;
631 old_stdhandles[0] = GetStdHandle (STD_INPUT_HANDLE);
632 SetStdHandle (STD_INPUT_HANDLE, h);
635 /* Scan the whole command looking for > and 2> */
636 redir = redirects;
637 while (redir != NULL && ((p = strchrW(redir,'>')) != NULL)) {
638 int handle = 0;
640 if (*(p-1)!='2') {
641 handle = 1;
642 } else {
643 handle = 2;
646 p++;
647 if ('>' == *p) {
648 creationDisposition = OPEN_ALWAYS;
649 p++;
651 else {
652 creationDisposition = CREATE_ALWAYS;
655 /* Add support for 2>&1 */
656 redir = p;
657 if (*p == '&') {
658 int idx = *(p+1) - '0';
660 if (DuplicateHandle(GetCurrentProcess(),
661 GetStdHandle(idx_stdhandles[idx]),
662 GetCurrentProcess(),
664 0, TRUE, DUPLICATE_SAME_ACCESS) == 0) {
665 WINE_FIXME("Duplicating handle failed with gle %d\n", GetLastError());
667 WINE_TRACE("Redirect %d (%p) to %d (%p)\n", handle, GetStdHandle(idx_stdhandles[idx]), idx, h);
669 } else {
670 WCHAR *param = WCMD_parameter (p, 0, NULL);
671 h = CreateFile (param, GENERIC_WRITE, 0, &sa, creationDisposition,
672 FILE_ATTRIBUTE_NORMAL, NULL);
673 if (h == INVALID_HANDLE_VALUE) {
674 WCMD_print_error ();
675 HeapFree( GetProcessHeap(), 0, cmd );
676 return;
678 if (SetFilePointer (h, 0, NULL, FILE_END) ==
679 INVALID_SET_FILE_POINTER) {
680 WCMD_print_error ();
682 WINE_TRACE("Redirect %d to '%s' (%p)\n", handle, wine_dbgstr_w(param), h);
685 old_stdhandles[handle] = GetStdHandle (idx_stdhandles[handle]);
686 SetStdHandle (idx_stdhandles[handle], h);
690 * Strip leading whitespaces, and a '@' if supplied
692 whichcmd = WCMD_strtrim_leading_spaces(cmd);
693 WINE_TRACE("Command: '%s'\n", wine_dbgstr_w(cmd));
694 if (whichcmd[0] == '@') whichcmd++;
697 * Check if the command entered is internal. If it is, pass the rest of the
698 * line down to the command. If not try to run a program.
701 count = 0;
702 while (IsCharAlphaNumeric(whichcmd[count])) {
703 count++;
705 for (i=0; i<=WCMD_EXIT; i++) {
706 if (CompareString (LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
707 whichcmd, count, inbuilt[i], -1) == 2) break;
709 p = WCMD_strtrim_leading_spaces (&whichcmd[count]);
710 WCMD_parse (p, quals, param1, param2);
711 WINE_TRACE("param1: %s, param2: %s\n", wine_dbgstr_w(param1), wine_dbgstr_w(param2));
713 switch (i) {
715 case WCMD_ATTRIB:
716 WCMD_setshow_attrib ();
717 break;
718 case WCMD_CALL:
719 WCMD_call (p);
720 break;
721 case WCMD_CD:
722 case WCMD_CHDIR:
723 WCMD_setshow_default (p);
724 break;
725 case WCMD_CLS:
726 WCMD_clear_screen ();
727 break;
728 case WCMD_COPY:
729 WCMD_copy ();
730 break;
731 case WCMD_CTTY:
732 WCMD_change_tty ();
733 break;
734 case WCMD_DATE:
735 WCMD_setshow_date ();
736 break;
737 case WCMD_DEL:
738 case WCMD_ERASE:
739 WCMD_delete (p, TRUE);
740 break;
741 case WCMD_DIR:
742 WCMD_directory (p);
743 break;
744 case WCMD_ECHO:
745 WCMD_echo(&whichcmd[count]);
746 break;
747 case WCMD_FOR:
748 WCMD_for (p, cmdList);
749 break;
750 case WCMD_GOTO:
751 WCMD_goto (cmdList);
752 break;
753 case WCMD_HELP:
754 WCMD_give_help (p);
755 break;
756 case WCMD_IF:
757 WCMD_if (p, cmdList);
758 break;
759 case WCMD_LABEL:
760 WCMD_volume (1, p);
761 break;
762 case WCMD_MD:
763 case WCMD_MKDIR:
764 WCMD_create_dir ();
765 break;
766 case WCMD_MOVE:
767 WCMD_move ();
768 break;
769 case WCMD_PATH:
770 WCMD_setshow_path (p);
771 break;
772 case WCMD_PAUSE:
773 WCMD_pause ();
774 break;
775 case WCMD_PROMPT:
776 WCMD_setshow_prompt ();
777 break;
778 case WCMD_REM:
779 break;
780 case WCMD_REN:
781 case WCMD_RENAME:
782 WCMD_rename ();
783 break;
784 case WCMD_RD:
785 case WCMD_RMDIR:
786 WCMD_remove_dir (p);
787 break;
788 case WCMD_SETLOCAL:
789 WCMD_setlocal(p);
790 break;
791 case WCMD_ENDLOCAL:
792 WCMD_endlocal();
793 break;
794 case WCMD_SET:
795 WCMD_setshow_env (p);
796 break;
797 case WCMD_SHIFT:
798 WCMD_shift (p);
799 break;
800 case WCMD_TIME:
801 WCMD_setshow_time ();
802 break;
803 case WCMD_TITLE:
804 if (strlenW(&whichcmd[count]) > 0)
805 WCMD_title(&whichcmd[count+1]);
806 break;
807 case WCMD_TYPE:
808 WCMD_type (p);
809 break;
810 case WCMD_VER:
811 WCMD_version ();
812 break;
813 case WCMD_VERIFY:
814 WCMD_verify (p);
815 break;
816 case WCMD_VOL:
817 WCMD_volume (0, p);
818 break;
819 case WCMD_PUSHD:
820 WCMD_pushd(p);
821 break;
822 case WCMD_POPD:
823 WCMD_popd();
824 break;
825 case WCMD_ASSOC:
826 WCMD_assoc(p, TRUE);
827 break;
828 case WCMD_COLOR:
829 WCMD_color();
830 break;
831 case WCMD_FTYPE:
832 WCMD_assoc(p, FALSE);
833 break;
834 case WCMD_MORE:
835 WCMD_more(p);
836 break;
837 case WCMD_EXIT:
838 WCMD_exit (cmdList);
839 break;
840 default:
841 WCMD_run_program (whichcmd, 0);
843 HeapFree( GetProcessHeap(), 0, cmd );
845 /* Restore old handles */
846 for (i=0; i<3; i++) {
847 if (old_stdhandles[i] != INVALID_HANDLE_VALUE) {
848 CloseHandle (GetStdHandle (idx_stdhandles[i]));
849 SetStdHandle (idx_stdhandles[i], old_stdhandles[i]);
854 static void init_msvcrt_io_block(STARTUPINFO* st)
856 STARTUPINFO st_p;
857 /* fetch the parent MSVCRT info block if any, so that the child can use the
858 * same handles as its grand-father
860 st_p.cb = sizeof(STARTUPINFO);
861 GetStartupInfo(&st_p);
862 st->cbReserved2 = st_p.cbReserved2;
863 st->lpReserved2 = st_p.lpReserved2;
864 if (st_p.cbReserved2 && st_p.lpReserved2)
866 /* Override the entries for fd 0,1,2 if we happened
867 * to change those std handles (this depends on the way wcmd sets
868 * it's new input & output handles)
870 size_t sz = max(sizeof(unsigned) + (sizeof(char) + sizeof(HANDLE)) * 3, st_p.cbReserved2);
871 BYTE* ptr = HeapAlloc(GetProcessHeap(), 0, sz);
872 if (ptr)
874 unsigned num = *(unsigned*)st_p.lpReserved2;
875 char* flags = (char*)(ptr + sizeof(unsigned));
876 HANDLE* handles = (HANDLE*)(flags + num * sizeof(char));
878 memcpy(ptr, st_p.lpReserved2, st_p.cbReserved2);
879 st->cbReserved2 = sz;
880 st->lpReserved2 = ptr;
882 #define WX_OPEN 0x01 /* see dlls/msvcrt/file.c */
883 if (num <= 0 || (flags[0] & WX_OPEN))
885 handles[0] = GetStdHandle(STD_INPUT_HANDLE);
886 flags[0] |= WX_OPEN;
888 if (num <= 1 || (flags[1] & WX_OPEN))
890 handles[1] = GetStdHandle(STD_OUTPUT_HANDLE);
891 flags[1] |= WX_OPEN;
893 if (num <= 2 || (flags[2] & WX_OPEN))
895 handles[2] = GetStdHandle(STD_ERROR_HANDLE);
896 flags[2] |= WX_OPEN;
898 #undef WX_OPEN
903 /******************************************************************************
904 * WCMD_run_program
906 * Execute a command line as an external program. Must allow recursion.
908 * Precedence:
909 * Manual testing under windows shows PATHEXT plays a key part in this,
910 * and the search algorithm and precedence appears to be as follows.
912 * Search locations:
913 * If directory supplied on command, just use that directory
914 * If extension supplied on command, look for that explicit name first
915 * Otherwise, search in each directory on the path
916 * Precedence:
917 * If extension supplied on command, look for that explicit name first
918 * Then look for supplied name .* (even if extension supplied, so
919 * 'garbage.exe' will match 'garbage.exe.cmd')
920 * If any found, cycle through PATHEXT looking for name.exe one by one
921 * Launching
922 * Once a match has been found, it is launched - Code currently uses
923 * findexecutable to achieve this which is left untouched.
926 void WCMD_run_program (WCHAR *command, int called) {
928 WCHAR temp[MAX_PATH];
929 WCHAR pathtosearch[MAXSTRING];
930 WCHAR *pathposn;
931 WCHAR stemofsearch[MAX_PATH];
932 WCHAR *lastSlash;
933 WCHAR pathext[MAXSTRING];
934 BOOL extensionsupplied = FALSE;
935 BOOL launched = FALSE;
936 BOOL status;
937 BOOL assumeInternal = FALSE;
938 DWORD len;
939 static const WCHAR envPath[] = {'P','A','T','H','\0'};
940 static const WCHAR envPathExt[] = {'P','A','T','H','E','X','T','\0'};
941 static const WCHAR delims[] = {'/','\\',':','\0'};
943 WCMD_parse (command, quals, param1, param2); /* Quick way to get the filename */
944 if (!(*param1) && !(*param2))
945 return;
947 /* Calculate the search path and stem to search for */
948 if (strpbrkW (param1, delims) == NULL) { /* No explicit path given, search path */
949 static const WCHAR curDir[] = {'.',';','\0'};
950 strcpyW(pathtosearch, curDir);
951 len = GetEnvironmentVariable (envPath, &pathtosearch[2], (sizeof(pathtosearch)/sizeof(WCHAR))-2);
952 if ((len == 0) || (len >= (sizeof(pathtosearch)/sizeof(WCHAR)) - 2)) {
953 static const WCHAR curDir[] = {'.','\0'};
954 strcpyW (pathtosearch, curDir);
956 if (strchrW(param1, '.') != NULL) extensionsupplied = TRUE;
957 strcpyW(stemofsearch, param1);
959 } else {
961 /* Convert eg. ..\fred to include a directory by removing file part */
962 GetFullPathName(param1, sizeof(pathtosearch)/sizeof(WCHAR), pathtosearch, NULL);
963 lastSlash = strrchrW(pathtosearch, '\\');
964 if (lastSlash && strchrW(lastSlash, '.') != NULL) extensionsupplied = TRUE;
965 strcpyW(stemofsearch, lastSlash+1);
967 /* Reduce pathtosearch to a path with trailing '\' to support c:\a.bat and
968 c:\windows\a.bat syntax */
969 if (lastSlash) *(lastSlash + 1) = 0x00;
972 /* Now extract PATHEXT */
973 len = GetEnvironmentVariable (envPathExt, pathext, sizeof(pathext)/sizeof(WCHAR));
974 if ((len == 0) || (len >= (sizeof(pathext)/sizeof(WCHAR)))) {
975 static const WCHAR dfltPathExt[] = {'.','b','a','t',';',
976 '.','c','o','m',';',
977 '.','c','m','d',';',
978 '.','e','x','e','\0'};
979 strcpyW (pathext, dfltPathExt);
982 /* Loop through the search path, dir by dir */
983 pathposn = pathtosearch;
984 WINE_TRACE("Searching in '%s' for '%s'\n", wine_dbgstr_w(pathtosearch),
985 wine_dbgstr_w(stemofsearch));
986 while (!launched && pathposn) {
988 WCHAR thisDir[MAX_PATH] = {'\0'};
989 WCHAR *pos = NULL;
990 BOOL found = FALSE;
991 const WCHAR slashW[] = {'\\','\0'};
993 /* Work on the first directory on the search path */
994 pos = strchrW(pathposn, ';');
995 if (pos) {
996 memcpy(thisDir, pathposn, (pos-pathposn) * sizeof(WCHAR));
997 thisDir[(pos-pathposn)] = 0x00;
998 pathposn = pos+1;
1000 } else {
1001 strcpyW(thisDir, pathposn);
1002 pathposn = NULL;
1005 /* Since you can have eg. ..\.. on the path, need to expand
1006 to full information */
1007 strcpyW(temp, thisDir);
1008 GetFullPathName(temp, MAX_PATH, thisDir, NULL);
1010 /* 1. If extension supplied, see if that file exists */
1011 strcatW(thisDir, slashW);
1012 strcatW(thisDir, stemofsearch);
1013 pos = &thisDir[strlenW(thisDir)]; /* Pos = end of name */
1015 /* 1. If extension supplied, see if that file exists */
1016 if (extensionsupplied) {
1017 if (GetFileAttributes(thisDir) != INVALID_FILE_ATTRIBUTES) {
1018 found = TRUE;
1022 /* 2. Any .* matches? */
1023 if (!found) {
1024 HANDLE h;
1025 WIN32_FIND_DATA finddata;
1026 static const WCHAR allFiles[] = {'.','*','\0'};
1028 strcatW(thisDir,allFiles);
1029 h = FindFirstFile(thisDir, &finddata);
1030 FindClose(h);
1031 if (h != INVALID_HANDLE_VALUE) {
1033 WCHAR *thisExt = pathext;
1035 /* 3. Yes - Try each path ext */
1036 while (thisExt) {
1037 WCHAR *nextExt = strchrW(thisExt, ';');
1039 if (nextExt) {
1040 memcpy(pos, thisExt, (nextExt-thisExt) * sizeof(WCHAR));
1041 pos[(nextExt-thisExt)] = 0x00;
1042 thisExt = nextExt+1;
1043 } else {
1044 strcpyW(pos, thisExt);
1045 thisExt = NULL;
1048 if (GetFileAttributes(thisDir) != INVALID_FILE_ATTRIBUTES) {
1049 found = TRUE;
1050 thisExt = NULL;
1056 /* Internal programs won't be picked up by this search, so even
1057 though not found, try one last createprocess and wait for it
1058 to complete.
1059 Note: Ideally we could tell between a console app (wait) and a
1060 windows app, but the API's for it fail in this case */
1061 if (!found && pathposn == NULL) {
1062 WINE_TRACE("ASSUMING INTERNAL\n");
1063 assumeInternal = TRUE;
1064 } else {
1065 WINE_TRACE("Found as %s\n", wine_dbgstr_w(thisDir));
1068 /* Once found, launch it */
1069 if (found || assumeInternal) {
1070 STARTUPINFO st;
1071 PROCESS_INFORMATION pe;
1072 SHFILEINFO psfi;
1073 DWORD console;
1074 HINSTANCE hinst;
1075 WCHAR *ext = strrchrW( thisDir, '.' );
1076 static const WCHAR batExt[] = {'.','b','a','t','\0'};
1077 static const WCHAR cmdExt[] = {'.','c','m','d','\0'};
1079 launched = TRUE;
1081 /* Special case BAT and CMD */
1082 if (ext && !strcmpiW(ext, batExt)) {
1083 WCMD_batch (thisDir, command, called, NULL, INVALID_HANDLE_VALUE);
1084 return;
1085 } else if (ext && !strcmpiW(ext, cmdExt)) {
1086 WCMD_batch (thisDir, command, called, NULL, INVALID_HANDLE_VALUE);
1087 return;
1088 } else {
1090 /* thisDir contains the file to be launched, but with what?
1091 eg. a.exe will require a.exe to be launched, a.html may be iexplore */
1092 hinst = FindExecutable (thisDir, NULL, temp);
1093 if ((INT_PTR)hinst < 32)
1094 console = 0;
1095 else
1096 console = SHGetFileInfo (temp, 0, &psfi, sizeof(psfi), SHGFI_EXETYPE);
1098 ZeroMemory (&st, sizeof(STARTUPINFO));
1099 st.cb = sizeof(STARTUPINFO);
1100 init_msvcrt_io_block(&st);
1102 /* Launch the process and if a CUI wait on it to complete
1103 Note: Launching internal wine processes cannot specify a full path to exe */
1104 status = CreateProcess (assumeInternal?NULL : thisDir,
1105 command, NULL, NULL, TRUE, 0, NULL, NULL, &st, &pe);
1106 if ((opt_c || opt_k) && !opt_s && !status
1107 && GetLastError()==ERROR_FILE_NOT_FOUND && command[0]=='\"') {
1108 /* strip first and last quote WCHARacters and try again */
1109 WCMD_opt_s_strip_quotes(command);
1110 opt_s=1;
1111 WCMD_run_program(command, called);
1112 return;
1114 if (!status) {
1115 WCMD_print_error ();
1116 /* If a command fails to launch, it sets errorlevel 9009 - which
1117 does not seem to have any associated constant definition */
1118 errorlevel = 9009;
1119 return;
1121 if (!assumeInternal && !console) errorlevel = 0;
1122 else
1124 /* Always wait when called in a batch program context */
1125 if (assumeInternal || context || !HIWORD(console)) WaitForSingleObject (pe.hProcess, INFINITE);
1126 GetExitCodeProcess (pe.hProcess, &errorlevel);
1127 if (errorlevel == STILL_ACTIVE) errorlevel = 0;
1129 CloseHandle(pe.hProcess);
1130 CloseHandle(pe.hThread);
1131 return;
1136 /* Not found anywhere - give up */
1137 SetLastError(ERROR_FILE_NOT_FOUND);
1138 WCMD_print_error ();
1140 /* If a command fails to launch, it sets errorlevel 9009 - which
1141 does not seem to have any associated constant definition */
1142 errorlevel = 9009;
1143 return;
1147 /******************************************************************************
1148 * WCMD_show_prompt
1150 * Display the prompt on STDout
1154 void WCMD_show_prompt (void) {
1156 int status;
1157 WCHAR out_string[MAX_PATH], curdir[MAX_PATH], prompt_string[MAX_PATH];
1158 WCHAR *p, *q;
1159 DWORD len;
1160 static const WCHAR envPrompt[] = {'P','R','O','M','P','T','\0'};
1162 len = GetEnvironmentVariable (envPrompt, prompt_string,
1163 sizeof(prompt_string)/sizeof(WCHAR));
1164 if ((len == 0) || (len >= (sizeof(prompt_string)/sizeof(WCHAR)))) {
1165 const WCHAR dfltPrompt[] = {'$','P','$','G','\0'};
1166 strcpyW (prompt_string, dfltPrompt);
1168 p = prompt_string;
1169 q = out_string;
1170 *q = '\0';
1171 while (*p != '\0') {
1172 if (*p != '$') {
1173 *q++ = *p++;
1174 *q = '\0';
1176 else {
1177 p++;
1178 switch (toupper(*p)) {
1179 case '$':
1180 *q++ = '$';
1181 break;
1182 case 'A':
1183 *q++ = '&';
1184 break;
1185 case 'B':
1186 *q++ = '|';
1187 break;
1188 case 'C':
1189 *q++ = '(';
1190 break;
1191 case 'D':
1192 GetDateFormat (LOCALE_USER_DEFAULT, DATE_SHORTDATE, NULL, NULL, q, MAX_PATH);
1193 while (*q) q++;
1194 break;
1195 case 'E':
1196 *q++ = '\E';
1197 break;
1198 case 'F':
1199 *q++ = ')';
1200 break;
1201 case 'G':
1202 *q++ = '>';
1203 break;
1204 case 'H':
1205 *q++ = '\b';
1206 break;
1207 case 'L':
1208 *q++ = '<';
1209 break;
1210 case 'N':
1211 status = GetCurrentDirectory (sizeof(curdir)/sizeof(WCHAR), curdir);
1212 if (status) {
1213 *q++ = curdir[0];
1215 break;
1216 case 'P':
1217 status = GetCurrentDirectory (sizeof(curdir)/sizeof(WCHAR), curdir);
1218 if (status) {
1219 strcatW (q, curdir);
1220 while (*q) q++;
1222 break;
1223 case 'Q':
1224 *q++ = '=';
1225 break;
1226 case 'S':
1227 *q++ = ' ';
1228 break;
1229 case 'T':
1230 GetTimeFormat (LOCALE_USER_DEFAULT, 0, NULL, NULL, q, MAX_PATH);
1231 while (*q) q++;
1232 break;
1233 case 'V':
1234 strcatW (q, version_string);
1235 while (*q) q++;
1236 break;
1237 case '_':
1238 *q++ = '\n';
1239 break;
1240 case '+':
1241 if (pushd_directories) {
1242 memset(q, '+', pushd_directories->u.stackdepth);
1243 q = q + pushd_directories->u.stackdepth;
1245 break;
1247 p++;
1248 *q = '\0';
1251 WCMD_output_asis (out_string);
1254 /****************************************************************************
1255 * WCMD_print_error
1257 * Print the message for GetLastError
1260 void WCMD_print_error (void) {
1261 LPVOID lpMsgBuf;
1262 DWORD error_code;
1263 int status;
1265 error_code = GetLastError ();
1266 status = FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
1267 NULL, error_code, 0, (LPTSTR) &lpMsgBuf, 0, NULL);
1268 if (!status) {
1269 WINE_FIXME ("Cannot display message for error %d, status %d\n",
1270 error_code, GetLastError());
1271 return;
1274 WCMD_output_asis_len(lpMsgBuf, lstrlen(lpMsgBuf),
1275 GetStdHandle(STD_ERROR_HANDLE));
1276 LocalFree ((HLOCAL)lpMsgBuf);
1277 WCMD_output_asis_len (newline, lstrlen(newline),
1278 GetStdHandle(STD_ERROR_HANDLE));
1279 return;
1282 /*******************************************************************
1283 * WCMD_parse - parse a command into parameters and qualifiers.
1285 * On exit, all qualifiers are concatenated into q, the first string
1286 * not beginning with "/" is in p1 and the
1287 * second in p2. Any subsequent non-qualifier strings are lost.
1288 * Parameters in quotes are handled.
1291 void WCMD_parse (WCHAR *s, WCHAR *q, WCHAR *p1, WCHAR *p2) {
1293 int p = 0;
1295 *q = *p1 = *p2 = '\0';
1296 while (TRUE) {
1297 switch (*s) {
1298 case '/':
1299 *q++ = *s++;
1300 while ((*s != '\0') && (*s != ' ') && *s != '/') {
1301 *q++ = toupperW (*s++);
1303 *q = '\0';
1304 break;
1305 case ' ':
1306 case '\t':
1307 s++;
1308 break;
1309 case '"':
1310 s++;
1311 while ((*s != '\0') && (*s != '"')) {
1312 if (p == 0) *p1++ = *s++;
1313 else if (p == 1) *p2++ = *s++;
1314 else s++;
1316 if (p == 0) *p1 = '\0';
1317 if (p == 1) *p2 = '\0';
1318 p++;
1319 if (*s == '"') s++;
1320 break;
1321 case '\0':
1322 return;
1323 default:
1324 while ((*s != '\0') && (*s != ' ') && (*s != '\t')
1325 && (*s != '=') && (*s != ',') ) {
1326 if (p == 0) *p1++ = *s++;
1327 else if (p == 1) *p2++ = *s++;
1328 else s++;
1330 /* Skip concurrent parms */
1331 while ((*s == ' ') || (*s == '\t') || (*s == '=') || (*s == ',') ) s++;
1333 if (p == 0) *p1 = '\0';
1334 if (p == 1) *p2 = '\0';
1335 p++;
1340 /*******************************************************************
1341 * WCMD_output_asis_len - send output to current standard output
1343 * Output a formatted unicode string. Ideally this will go to the console
1344 * and hence required WriteConsoleW to output it, however if file i/o is
1345 * redirected, it needs to be WriteFile'd using OEM (not ANSI) format
1347 static void WCMD_output_asis_len(const WCHAR *message, int len, HANDLE device) {
1349 DWORD nOut= 0;
1350 DWORD res = 0;
1352 /* If nothing to write, return (MORE does this sometimes) */
1353 if (!len) return;
1355 /* Try to write as unicode assuming it is to a console */
1356 res = WriteConsoleW(device, message, len, &nOut, NULL);
1358 /* If writing to console fails, assume its file
1359 i/o so convert to OEM codepage and output */
1360 if (!res) {
1361 BOOL usedDefaultChar = FALSE;
1362 DWORD convertedChars;
1364 if (!unicodePipes) {
1366 * Allocate buffer to use when writing to file. (Not freed, as one off)
1368 if (!output_bufA) output_bufA = HeapAlloc(GetProcessHeap(), 0,
1369 MAX_WRITECONSOLE_SIZE);
1370 if (!output_bufA) {
1371 WINE_FIXME("Out of memory - could not allocate ansi 64K buffer\n");
1372 return;
1375 /* Convert to OEM, then output */
1376 convertedChars = WideCharToMultiByte(GetConsoleOutputCP(), 0, message,
1377 len, output_bufA, MAX_WRITECONSOLE_SIZE,
1378 "?", &usedDefaultChar);
1379 WriteFile(device, output_bufA, convertedChars,
1380 &nOut, FALSE);
1381 } else {
1382 WriteFile(device, message, len*sizeof(WCHAR),
1383 &nOut, FALSE);
1386 return;
1389 /*******************************************************************
1390 * WCMD_output - send output to current standard output device.
1394 void WCMD_output (const WCHAR *format, ...) {
1396 va_list ap;
1397 WCHAR string[1024];
1398 int ret;
1400 va_start(ap,format);
1401 ret = wvsprintf (string, format, ap);
1402 if( ret >= (sizeof(string)/sizeof(WCHAR))) {
1403 WINE_ERR("Output truncated in WCMD_output\n" );
1404 ret = (sizeof(string)/sizeof(WCHAR)) - 1;
1405 string[ret] = '\0';
1407 va_end(ap);
1408 WCMD_output_asis_len(string, ret, GetStdHandle(STD_OUTPUT_HANDLE));
1412 static int line_count;
1413 static int max_height;
1414 static int max_width;
1415 static BOOL paged_mode;
1416 static int numChars;
1418 void WCMD_enter_paged_mode(const WCHAR *msg)
1420 CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
1422 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &consoleInfo)) {
1423 max_height = consoleInfo.dwSize.Y;
1424 max_width = consoleInfo.dwSize.X;
1425 } else {
1426 max_height = 25;
1427 max_width = 80;
1429 paged_mode = TRUE;
1430 line_count = 0;
1431 numChars = 0;
1432 pagedMessage = (msg==NULL)? anykey : msg;
1435 void WCMD_leave_paged_mode(void)
1437 paged_mode = FALSE;
1438 pagedMessage = NULL;
1441 /*******************************************************************
1442 * WCMD_output_asis - send output to current standard output device.
1443 * without formatting eg. when message contains '%'
1446 void WCMD_output_asis (const WCHAR *message) {
1447 DWORD count;
1448 const WCHAR* ptr;
1449 WCHAR string[1024];
1451 if (paged_mode) {
1452 do {
1453 ptr = message;
1454 while (*ptr && *ptr!='\n' && (numChars < max_width)) {
1455 numChars++;
1456 ptr++;
1458 if (*ptr == '\n') ptr++;
1459 WCMD_output_asis_len(message, (ptr) ? ptr - message : strlenW(message),
1460 GetStdHandle(STD_OUTPUT_HANDLE));
1461 if (ptr) {
1462 numChars = 0;
1463 if (++line_count >= max_height - 1) {
1464 line_count = 0;
1465 WCMD_output_asis_len(pagedMessage, strlenW(pagedMessage),
1466 GetStdHandle(STD_OUTPUT_HANDLE));
1467 WCMD_ReadFile (GetStdHandle(STD_INPUT_HANDLE), string,
1468 sizeof(string)/sizeof(WCHAR), &count, NULL);
1471 } while (((message = ptr) != NULL) && (*ptr));
1472 } else {
1473 WCMD_output_asis_len(message, lstrlen(message),
1474 GetStdHandle(STD_OUTPUT_HANDLE));
1479 /***************************************************************************
1480 * WCMD_strtrim_leading_spaces
1482 * Remove leading spaces from a string. Return a pointer to the first
1483 * non-space character. Does not modify the input string
1486 WCHAR *WCMD_strtrim_leading_spaces (WCHAR *string) {
1488 WCHAR *ptr;
1490 ptr = string;
1491 while (*ptr == ' ') ptr++;
1492 return ptr;
1495 /*************************************************************************
1496 * WCMD_strtrim_trailing_spaces
1498 * Remove trailing spaces from a string. This routine modifies the input
1499 * string by placing a null after the last non-space WCHARacter
1502 void WCMD_strtrim_trailing_spaces (WCHAR *string) {
1504 WCHAR *ptr;
1506 ptr = string + strlenW (string) - 1;
1507 while ((*ptr == ' ') && (ptr >= string)) {
1508 *ptr = '\0';
1509 ptr--;
1513 /*************************************************************************
1514 * WCMD_opt_s_strip_quotes
1516 * Remove first and last quote WCHARacters, preserving all other text
1519 void WCMD_opt_s_strip_quotes(WCHAR *cmd) {
1520 WCHAR *src = cmd + 1, *dest = cmd, *lastq = NULL;
1521 while((*dest=*src) != '\0') {
1522 if (*src=='\"')
1523 lastq=dest;
1524 dest++, src++;
1526 if (lastq) {
1527 dest=lastq++;
1528 while ((*dest++=*lastq++) != 0)
1533 /*************************************************************************
1534 * WCMD_pipe
1536 * Handle pipes within a command - the DOS way using temporary files.
1539 void WCMD_pipe (CMD_LIST **cmdEntry, WCHAR *var, WCHAR *val) {
1541 WCHAR *p;
1542 WCHAR *command = (*cmdEntry)->command;
1543 WCHAR temp_path[MAX_PATH], temp_file[MAX_PATH], temp_file2[MAX_PATH], temp_cmd[1024];
1544 static const WCHAR redirOut[] = {'%','s',' ','>',' ','%','s','\0'};
1545 static const WCHAR redirIn[] = {'%','s',' ','<',' ','%','s','\0'};
1546 static const WCHAR redirBoth[]= {'%','s',' ','<',' ','%','s',' ','>','%','s','\0'};
1547 static const WCHAR cmdW[] = {'C','M','D','\0'};
1550 GetTempPath (sizeof(temp_path)/sizeof(WCHAR), temp_path);
1551 GetTempFileName (temp_path, cmdW, 0, temp_file);
1552 p = strchrW(command, '|');
1553 *p++ = '\0';
1554 wsprintf (temp_cmd, redirOut, command, temp_file);
1555 WCMD_execute (temp_cmd, (*cmdEntry)->redirects, var, val, cmdEntry);
1556 command = p;
1557 while ((p = strchrW(command, '|'))) {
1558 *p++ = '\0';
1559 GetTempFileName (temp_path, cmdW, 0, temp_file2);
1560 wsprintf (temp_cmd, redirBoth, command, temp_file, temp_file2);
1561 WCMD_execute (temp_cmd, (*cmdEntry)->redirects, var, val, cmdEntry);
1562 DeleteFile (temp_file);
1563 strcpyW (temp_file, temp_file2);
1564 command = p;
1566 wsprintf (temp_cmd, redirIn, command, temp_file);
1567 WCMD_execute (temp_cmd, (*cmdEntry)->redirects, var, val, cmdEntry);
1568 DeleteFile (temp_file);
1571 /*************************************************************************
1572 * WCMD_expand_envvar
1574 * Expands environment variables, allowing for WCHARacter substitution
1576 static WCHAR *WCMD_expand_envvar(WCHAR *start, WCHAR *forVar, WCHAR *forVal) {
1577 WCHAR *endOfVar = NULL, *s;
1578 WCHAR *colonpos = NULL;
1579 WCHAR thisVar[MAXSTRING];
1580 WCHAR thisVarContents[MAXSTRING];
1581 WCHAR savedchar = 0x00;
1582 int len;
1584 static const WCHAR ErrorLvl[] = {'E','R','R','O','R','L','E','V','E','L','\0'};
1585 static const WCHAR ErrorLvlP[] = {'%','E','R','R','O','R','L','E','V','E','L','%','\0'};
1586 static const WCHAR Date[] = {'D','A','T','E','\0'};
1587 static const WCHAR DateP[] = {'%','D','A','T','E','%','\0'};
1588 static const WCHAR Time[] = {'T','I','M','E','\0'};
1589 static const WCHAR TimeP[] = {'%','T','I','M','E','%','\0'};
1590 static const WCHAR Cd[] = {'C','D','\0'};
1591 static const WCHAR CdP[] = {'%','C','D','%','\0'};
1592 static const WCHAR Random[] = {'R','A','N','D','O','M','\0'};
1593 static const WCHAR RandomP[] = {'%','R','A','N','D','O','M','%','\0'};
1594 static const WCHAR Delims[] = {'%',' ',':','\0'};
1596 WINE_TRACE("Expanding: %s (%s,%s)\n", wine_dbgstr_w(start),
1597 wine_dbgstr_w(forVal), wine_dbgstr_w(forVar));
1599 /* Find the end of the environment variable, and extract name */
1600 endOfVar = strpbrkW(start+1, Delims);
1602 if (endOfVar == NULL || *endOfVar==' ') {
1604 /* In batch program, missing terminator for % and no following
1605 ':' just removes the '%' */
1606 if (context) {
1607 s = WCMD_strdupW(start + 1);
1608 strcpyW (start, s);
1609 free(s);
1610 return start;
1611 } else {
1613 /* In command processing, just ignore it - allows command line
1614 syntax like: for %i in (a.a) do echo %i */
1615 return start+1;
1619 /* If ':' found, process remaining up until '%' (or stop at ':' if
1620 a missing '%' */
1621 if (*endOfVar==':') {
1622 WCHAR *endOfVar2 = strchrW(endOfVar+1, '%');
1623 if (endOfVar2 != NULL) endOfVar = endOfVar2;
1626 memcpy(thisVar, start, ((endOfVar - start) + 1) * sizeof(WCHAR));
1627 thisVar[(endOfVar - start)+1] = 0x00;
1628 colonpos = strchrW(thisVar+1, ':');
1630 /* If there's complex substitution, just need %var% for now
1631 to get the expanded data to play with */
1632 if (colonpos) {
1633 *colonpos = '%';
1634 savedchar = *(colonpos+1);
1635 *(colonpos+1) = 0x00;
1638 WINE_TRACE("Retrieving contents of %s\n", wine_dbgstr_w(thisVar));
1640 /* Expand to contents, if unchanged, return */
1641 /* Handle DATE, TIME, ERRORLEVEL and CD replacements allowing */
1642 /* override if existing env var called that name */
1643 if ((CompareString (LOCALE_USER_DEFAULT,
1644 NORM_IGNORECASE | SORT_STRINGSORT,
1645 thisVar, 12, ErrorLvlP, -1) == 2) &&
1646 (GetEnvironmentVariable(ErrorLvl, thisVarContents, 1) == 0) &&
1647 (GetLastError() == ERROR_ENVVAR_NOT_FOUND)) {
1648 static const WCHAR fmt[] = {'%','d','\0'};
1649 wsprintf(thisVarContents, fmt, errorlevel);
1650 len = strlenW(thisVarContents);
1652 } else if ((CompareString (LOCALE_USER_DEFAULT,
1653 NORM_IGNORECASE | SORT_STRINGSORT,
1654 thisVar, 6, DateP, -1) == 2) &&
1655 (GetEnvironmentVariable(Date, thisVarContents, 1) == 0) &&
1656 (GetLastError() == ERROR_ENVVAR_NOT_FOUND)) {
1658 GetDateFormat(LOCALE_USER_DEFAULT, DATE_SHORTDATE, NULL,
1659 NULL, thisVarContents, MAXSTRING);
1660 len = strlenW(thisVarContents);
1662 } else if ((CompareString (LOCALE_USER_DEFAULT,
1663 NORM_IGNORECASE | SORT_STRINGSORT,
1664 thisVar, 6, TimeP, -1) == 2) &&
1665 (GetEnvironmentVariable(Time, thisVarContents, 1) == 0) &&
1666 (GetLastError() == ERROR_ENVVAR_NOT_FOUND)) {
1667 GetTimeFormat(LOCALE_USER_DEFAULT, TIME_NOSECONDS, NULL,
1668 NULL, thisVarContents, MAXSTRING);
1669 len = strlenW(thisVarContents);
1671 } else if ((CompareString (LOCALE_USER_DEFAULT,
1672 NORM_IGNORECASE | SORT_STRINGSORT,
1673 thisVar, 4, CdP, -1) == 2) &&
1674 (GetEnvironmentVariable(Cd, thisVarContents, 1) == 0) &&
1675 (GetLastError() == ERROR_ENVVAR_NOT_FOUND)) {
1676 GetCurrentDirectory (MAXSTRING, thisVarContents);
1677 len = strlenW(thisVarContents);
1679 } else if ((CompareString (LOCALE_USER_DEFAULT,
1680 NORM_IGNORECASE | SORT_STRINGSORT,
1681 thisVar, 8, RandomP, -1) == 2) &&
1682 (GetEnvironmentVariable(Random, thisVarContents, 1) == 0) &&
1683 (GetLastError() == ERROR_ENVVAR_NOT_FOUND)) {
1684 static const WCHAR fmt[] = {'%','d','\0'};
1685 wsprintf(thisVarContents, fmt, rand() % 32768);
1686 len = strlenW(thisVarContents);
1688 /* Look for a matching 'for' variable */
1689 } else if (forVar &&
1690 (CompareString (LOCALE_USER_DEFAULT,
1691 SORT_STRINGSORT,
1692 thisVar,
1693 (colonpos - thisVar) - 1,
1694 forVar, -1) == 2)) {
1695 strcpyW(thisVarContents, forVal);
1696 len = strlenW(thisVarContents);
1698 } else {
1700 len = ExpandEnvironmentStrings(thisVar, thisVarContents,
1701 sizeof(thisVarContents)/sizeof(WCHAR));
1704 if (len == 0)
1705 return endOfVar+1;
1707 /* In a batch program, unknown env vars are replaced with nothing,
1708 note syntax %garbage:1,3% results in anything after the ':'
1709 except the %
1710 From the command line, you just get back what you entered */
1711 if (lstrcmpiW(thisVar, thisVarContents) == 0) {
1713 /* Restore the complex part after the compare */
1714 if (colonpos) {
1715 *colonpos = ':';
1716 *(colonpos+1) = savedchar;
1719 /* Command line - just ignore this */
1720 if (context == NULL) return endOfVar+1;
1722 s = WCMD_strdupW(endOfVar + 1);
1724 /* Batch - replace unknown env var with nothing */
1725 if (colonpos == NULL) {
1726 strcpyW (start, s);
1728 } else {
1729 len = strlenW(thisVar);
1730 thisVar[len-1] = 0x00;
1731 /* If %:...% supplied, : is retained */
1732 if (colonpos == thisVar+1) {
1733 strcpyW (start, colonpos);
1734 } else {
1735 strcpyW (start, colonpos+1);
1737 strcatW (start, s);
1739 free (s);
1740 return start;
1744 /* See if we need to do complex substitution (any ':'s), if not
1745 then our work here is done */
1746 if (colonpos == NULL) {
1747 s = WCMD_strdupW(endOfVar + 1);
1748 strcpyW (start, thisVarContents);
1749 strcatW (start, s);
1750 free(s);
1751 return start;
1754 /* Restore complex bit */
1755 *colonpos = ':';
1756 *(colonpos+1) = savedchar;
1759 Handle complex substitutions:
1760 xxx=yyy (replace xxx with yyy)
1761 *xxx=yyy (replace up to and including xxx with yyy)
1762 ~x (from x WCHARs in)
1763 ~-x (from x WCHARs from the end)
1764 ~x,y (from x WCHARs in for y WCHARacters)
1765 ~x,-y (from x WCHARs in until y WCHARacters from the end)
1768 /* ~ is substring manipulation */
1769 if (savedchar == '~') {
1771 int substrposition, substrlength = 0;
1772 WCHAR *commapos = strchrW(colonpos+2, ',');
1773 WCHAR *startCopy;
1775 substrposition = atolW(colonpos+2);
1776 if (commapos) substrlength = atolW(commapos+1);
1778 s = WCMD_strdupW(endOfVar + 1);
1780 /* Check bounds */
1781 if (substrposition >= 0) {
1782 startCopy = &thisVarContents[min(substrposition, len)];
1783 } else {
1784 startCopy = &thisVarContents[max(0, len+substrposition-1)];
1787 if (commapos == NULL) {
1788 strcpyW (start, startCopy); /* Copy the lot */
1789 } else if (substrlength < 0) {
1791 int copybytes = (len+substrlength-1)-(startCopy-thisVarContents);
1792 if (copybytes > len) copybytes = len;
1793 else if (copybytes < 0) copybytes = 0;
1794 memcpy (start, startCopy, copybytes * sizeof(WCHAR)); /* Copy the lot */
1795 start[copybytes] = 0x00;
1796 } else {
1797 memcpy (start, startCopy, substrlength * sizeof(WCHAR)); /* Copy the lot */
1798 start[substrlength] = 0x00;
1801 strcatW (start, s);
1802 free(s);
1803 return start;
1805 /* search and replace manipulation */
1806 } else {
1807 WCHAR *equalspos = strstrW(colonpos, equalsW);
1808 WCHAR *replacewith = equalspos+1;
1809 WCHAR *found = NULL;
1810 WCHAR *searchIn;
1811 WCHAR *searchFor;
1813 s = WCMD_strdupW(endOfVar + 1);
1814 if (equalspos == NULL) return start+1;
1816 /* Null terminate both strings */
1817 thisVar[strlenW(thisVar)-1] = 0x00;
1818 *equalspos = 0x00;
1820 /* Since we need to be case insensitive, copy the 2 buffers */
1821 searchIn = WCMD_strdupW(thisVarContents);
1822 CharUpperBuff(searchIn, strlenW(thisVarContents));
1823 searchFor = WCMD_strdupW(colonpos+1);
1824 CharUpperBuff(searchFor, strlenW(colonpos+1));
1827 /* Handle wildcard case */
1828 if (*(colonpos+1) == '*') {
1829 /* Search for string to replace */
1830 found = strstrW(searchIn, searchFor+1);
1832 if (found) {
1833 /* Do replacement */
1834 strcpyW(start, replacewith);
1835 strcatW(start, thisVarContents + (found-searchIn) + strlenW(searchFor+1));
1836 strcatW(start, s);
1837 free(s);
1838 } else {
1839 /* Copy as it */
1840 strcpyW(start, thisVarContents);
1841 strcatW(start, s);
1844 } else {
1845 /* Loop replacing all instances */
1846 WCHAR *lastFound = searchIn;
1847 WCHAR *outputposn = start;
1849 *start = 0x00;
1850 while ((found = strstrW(lastFound, searchFor))) {
1851 lstrcpynW(outputposn,
1852 thisVarContents + (lastFound-searchIn),
1853 (found - lastFound)+1);
1854 outputposn = outputposn + (found - lastFound);
1855 strcatW(outputposn, replacewith);
1856 outputposn = outputposn + strlenW(replacewith);
1857 lastFound = found + strlenW(searchFor);
1859 strcatW(outputposn,
1860 thisVarContents + (lastFound-searchIn));
1861 strcatW(outputposn, s);
1863 free(searchIn);
1864 free(searchFor);
1865 return start;
1867 return start+1;
1870 /*************************************************************************
1871 * WCMD_LoadMessage
1872 * Load a string from the resource file, handling any error
1873 * Returns string retrieved from resource file
1875 WCHAR *WCMD_LoadMessage(UINT id) {
1876 static WCHAR msg[2048];
1877 static const WCHAR failedMsg[] = {'F','a','i','l','e','d','!','\0'};
1879 if (!LoadString(GetModuleHandle(NULL), id, msg, sizeof(msg)/sizeof(WCHAR))) {
1880 WINE_FIXME("LoadString failed with %d\n", GetLastError());
1881 strcpyW(msg, failedMsg);
1883 return msg;
1886 /*************************************************************************
1887 * WCMD_strdupW
1888 * A wide version of strdup as its missing from unicode.h
1890 WCHAR *WCMD_strdupW(WCHAR *input) {
1891 int len=strlenW(input)+1;
1892 /* Note: Use malloc not HeapAlloc to emulate strdup */
1893 WCHAR *result = malloc(len * sizeof(WCHAR));
1894 memcpy(result, input, len * sizeof(WCHAR));
1895 return result;
1898 /***************************************************************************
1899 * WCMD_Readfile
1901 * Read characters in from a console/file, returning result in Unicode
1902 * with signature identical to ReadFile
1904 BOOL WCMD_ReadFile(const HANDLE hIn, WCHAR *intoBuf, const DWORD maxChars,
1905 LPDWORD charsRead, const LPOVERLAPPED unused) {
1907 BOOL res;
1909 /* Try to read from console as Unicode */
1910 res = ReadConsoleW(hIn, intoBuf, maxChars, charsRead, NULL);
1912 /* If reading from console has failed we assume its file
1913 i/o so read in and convert from OEM codepage */
1914 if (!res) {
1916 DWORD numRead;
1918 * Allocate buffer to use when reading from file. Not freed
1920 if (!output_bufA) output_bufA = HeapAlloc(GetProcessHeap(), 0,
1921 MAX_WRITECONSOLE_SIZE);
1922 if (!output_bufA) {
1923 WINE_FIXME("Out of memory - could not allocate ansi 64K buffer\n");
1924 return 0;
1927 /* Read from file (assume OEM codepage) */
1928 res = ReadFile(hIn, output_bufA, maxChars, &numRead, unused);
1930 /* Convert from OEM */
1931 *charsRead = MultiByteToWideChar(GetConsoleCP(), 0, output_bufA, numRead,
1932 intoBuf, maxChars);
1935 return res;
1938 /***************************************************************************
1939 * WCMD_DumpCommands
1941 * Domps out the parsed command line to ensure syntax is correct
1943 void WCMD_DumpCommands(CMD_LIST *commands) {
1944 WCHAR buffer[MAXSTRING];
1945 CMD_LIST *thisCmd = commands;
1946 const WCHAR fmt[] = {'%','p',' ','%','c',' ','%','2','.','2','d',' ',
1947 '%','p',' ','%','s',' ','R','e','d','i','r',':',
1948 '%','s','\0'};
1950 WINE_TRACE("Parsed line:\n");
1951 while (thisCmd != NULL) {
1952 sprintfW(buffer, fmt,
1953 thisCmd,
1954 thisCmd->isAmphersand?'Y':'N',
1955 thisCmd->bracketDepth,
1956 thisCmd->nextcommand,
1957 thisCmd->command,
1958 thisCmd->redirects);
1959 WINE_TRACE("%s\n", wine_dbgstr_w(buffer));
1960 thisCmd = thisCmd->nextcommand;
1964 /***************************************************************************
1965 * WCMD_addCommand
1967 * Adds a command to the current command list
1969 void WCMD_addCommand(WCHAR *command, int *commandLen,
1970 WCHAR *redirs, int *redirLen,
1971 WCHAR **copyTo, int **copyToLen,
1972 BOOL isAmphersand, int curDepth,
1973 CMD_LIST **lastEntry, CMD_LIST **output) {
1975 CMD_LIST *thisEntry = NULL;
1977 /* Allocate storage for command */
1978 thisEntry = HeapAlloc(GetProcessHeap(), 0, sizeof(CMD_LIST));
1980 /* Copy in the command */
1981 if (command) {
1982 thisEntry->command = HeapAlloc(GetProcessHeap(), 0,
1983 (*commandLen+1) * sizeof(WCHAR));
1984 memcpy(thisEntry->command, command, *commandLen * sizeof(WCHAR));
1985 thisEntry->command[*commandLen] = 0x00;
1987 /* Copy in the redirects */
1988 thisEntry->redirects = HeapAlloc(GetProcessHeap(), 0,
1989 (*redirLen+1) * sizeof(WCHAR));
1990 memcpy(thisEntry->redirects, redirs, *redirLen * sizeof(WCHAR));
1991 thisEntry->redirects[*redirLen] = 0x00;
1993 /* Reset the lengths */
1994 *commandLen = 0;
1995 *redirLen = 0;
1996 *copyToLen = commandLen;
1997 *copyTo = command;
1999 } else {
2000 thisEntry->command = NULL;
2003 /* Fill in other fields */
2004 thisEntry->nextcommand = NULL;
2005 thisEntry->isAmphersand = isAmphersand;
2006 thisEntry->bracketDepth = curDepth;
2007 if (*lastEntry) {
2008 (*lastEntry)->nextcommand = thisEntry;
2009 } else {
2010 *output = thisEntry;
2012 *lastEntry = thisEntry;
2015 /***************************************************************************
2016 * WCMD_ReadAndParseLine
2018 * Either uses supplied input or
2019 * Reads a file from the handle, and then...
2020 * Parse the text buffer, spliting into separate commands
2021 * - unquoted && strings split 2 commands but the 2nd is flagged as
2022 * following an &&
2023 * - ( as the first character just ups the bracket depth
2024 * - unquoted ) when bracket depth > 0 terminates a bracket and
2025 * adds a CMD_LIST structure with null command
2026 * - Anything else gets put into the command string (including
2027 * redirects)
2029 WCHAR *WCMD_ReadAndParseLine(WCHAR *optionalcmd, CMD_LIST **output, HANDLE readFrom) {
2031 WCHAR *curPos;
2032 BOOL inQuotes = FALSE;
2033 WCHAR curString[MAXSTRING];
2034 int curStringLen = 0;
2035 WCHAR curRedirs[MAXSTRING];
2036 int curRedirsLen = 0;
2037 WCHAR *curCopyTo;
2038 int *curLen;
2039 int curDepth = 0;
2040 CMD_LIST *lastEntry = NULL;
2041 BOOL isAmphersand = FALSE;
2042 static WCHAR *extraSpace = NULL; /* Deliberately never freed */
2043 const WCHAR remCmd[] = {'r','e','m',' ','\0'};
2044 const WCHAR forCmd[] = {'f','o','r',' ','\0'};
2045 const WCHAR ifCmd[] = {'i','f',' ','\0'};
2046 const WCHAR ifElse[] = {'e','l','s','e',' ','\0'};
2047 BOOL inRem = FALSE;
2048 BOOL inFor = FALSE;
2049 BOOL inIn = FALSE;
2050 BOOL inIf = FALSE;
2051 BOOL inElse= FALSE;
2052 BOOL onlyWhiteSpace = FALSE;
2053 BOOL lastWasWhiteSpace = FALSE;
2054 BOOL lastWasDo = FALSE;
2055 BOOL lastWasIn = FALSE;
2056 BOOL lastWasElse = FALSE;
2057 BOOL lastWasRedirect = TRUE;
2059 /* Allocate working space for a command read from keyboard, file etc */
2060 if (!extraSpace)
2061 extraSpace = HeapAlloc(GetProcessHeap(), 0, (MAXSTRING+1) * sizeof(WCHAR));
2063 /* If initial command read in, use that, otherwise get input from handle */
2064 if (optionalcmd != NULL) {
2065 strcpyW(extraSpace, optionalcmd);
2066 } else if (readFrom == INVALID_HANDLE_VALUE) {
2067 WINE_FIXME("No command nor handle supplied\n");
2068 } else {
2069 if (WCMD_fgets(extraSpace, MAXSTRING, readFrom) == NULL) return NULL;
2071 curPos = extraSpace;
2073 /* Handle truncated input - issue warning */
2074 if (strlenW(extraSpace) == MAXSTRING -1) {
2075 WCMD_output_asis(WCMD_LoadMessage(WCMD_TRUNCATEDLINE));
2076 WCMD_output_asis(extraSpace);
2077 WCMD_output_asis(newline);
2080 /* Replace env vars if in a batch context */
2081 if (context) handleExpansion(extraSpace, FALSE, NULL, NULL);
2083 /* Start with an empty string, copying to the command string */
2084 curStringLen = 0;
2085 curRedirsLen = 0;
2086 curCopyTo = curString;
2087 curLen = &curStringLen;
2088 lastWasRedirect = FALSE; /* Required for eg spaces between > and filename */
2090 /* Parse every character on the line being processed */
2091 while (*curPos != 0x00) {
2093 WCHAR thisChar;
2095 /* Debugging AID:
2096 WINE_TRACE("Looking at '%c' (len:%d, lws:%d, ows:%d)\n", *curPos, *curLen,
2097 lastWasWhiteSpace, onlyWhiteSpace);
2100 /* Certain commands need special handling */
2101 if (curStringLen == 0 && curCopyTo == curString) {
2102 const WCHAR forDO[] = {'d','o',' ','\0'};
2104 /* If command starts with 'rem', ignore any &&, ( etc */
2105 if (CompareString (LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
2106 curPos, 4, remCmd, -1) == 2) {
2107 inRem = TRUE;
2109 /* If command starts with 'for', handle ('s mid line after IN or DO */
2110 } else if (CompareString (LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
2111 curPos, 4, forCmd, -1) == 2) {
2112 inFor = TRUE;
2114 /* If command starts with 'if' or 'else', handle ('s mid line. We should ensure this
2115 is only true in the command portion of the IF statement, but this
2116 should suffice for now
2117 FIXME: Silly syntax like "if 1(==1( (
2118 echo they equal
2119 )" will be parsed wrong */
2120 } else if (CompareString (LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
2121 curPos, 3, ifCmd, -1) == 2) {
2122 inIf = TRUE;
2124 } else if (CompareString (LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
2125 curPos, 5, ifElse, -1) == 2) {
2126 inElse = TRUE;
2127 lastWasElse = TRUE;
2128 onlyWhiteSpace = TRUE;
2129 memcpy(&curCopyTo[*curLen], curPos, 5*sizeof(WCHAR));
2130 (*curLen)+=5;
2131 curPos+=5;
2132 continue;
2134 /* In a for loop, the DO command will follow a close bracket followed by
2135 whitespace, followed by DO, ie closeBracket inserts a NULL entry, curLen
2136 is then 0, and all whitespace is skipped */
2137 } else if (inFor &&
2138 (CompareString (LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
2139 curPos, 3, forDO, -1) == 2)) {
2140 WINE_TRACE("Found DO\n");
2141 lastWasDo = TRUE;
2142 onlyWhiteSpace = TRUE;
2143 memcpy(&curCopyTo[*curLen], curPos, 3*sizeof(WCHAR));
2144 (*curLen)+=3;
2145 curPos+=3;
2146 continue;
2148 } else if (curCopyTo == curString) {
2150 /* Special handling for the 'FOR' command */
2151 if (inFor && lastWasWhiteSpace) {
2152 const WCHAR forIN[] = {'i','n',' ','\0'};
2154 WINE_TRACE("Found 'FOR', comparing next parm: '%s'\n", wine_dbgstr_w(curPos));
2156 if (CompareString (LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
2157 curPos, 3, forIN, -1) == 2) {
2158 WINE_TRACE("Found IN\n");
2159 lastWasIn = TRUE;
2160 onlyWhiteSpace = TRUE;
2161 memcpy(&curCopyTo[*curLen], curPos, 3*sizeof(WCHAR));
2162 (*curLen)+=3;
2163 curPos+=3;
2164 continue;
2169 /* Nothing 'ends' a REM statement and &&, quotes etc are ineffective,
2170 so just use the default processing ie skip character specific
2171 matching below */
2172 if (!inRem) thisChar = *curPos;
2173 else thisChar = 'X'; /* Character with no special processing */
2175 lastWasWhiteSpace = FALSE; /* Will be reset below */
2177 switch (thisChar) {
2179 case '=': /* drop through - ignore token delimiters at the start of a command */
2180 case ',': /* drop through - ignore token delimiters at the start of a command */
2181 case '\t':/* drop through - ignore token delimiters at the start of a command */
2182 case ' ':
2183 /* If a redirect in place, it ends here */
2184 if (!inQuotes && !lastWasRedirect) {
2186 /* If finishing off a redirect, add a whitespace delimiter */
2187 if (curCopyTo == curRedirs) {
2188 curCopyTo[(*curLen)++] = ' ';
2190 curCopyTo = curString;
2191 curLen = &curStringLen;
2193 if (*curLen > 0) {
2194 curCopyTo[(*curLen)++] = *curPos;
2197 /* Remember just processed whitespace */
2198 lastWasWhiteSpace = TRUE;
2200 break;
2202 case '>': /* drop through - handle redirect chars the same */
2203 case '<':
2204 /* Make a redirect start here */
2205 if (!inQuotes) {
2206 curCopyTo = curRedirs;
2207 curLen = &curRedirsLen;
2208 lastWasRedirect = TRUE;
2211 /* See if 1>, 2> etc, in which case we have some patching up
2212 to do */
2213 if (curPos != extraSpace &&
2214 *(curPos-1)>='1' && *(curPos-1)<='9') {
2216 curStringLen--;
2217 curString[curStringLen] = 0x00;
2218 curCopyTo[(*curLen)++] = *(curPos-1);
2221 curCopyTo[(*curLen)++] = *curPos;
2222 break;
2224 case '|': /* Pipe character only if not || */
2225 if (!inQuotes && *(curPos++) == '|') {
2227 /* || is an alternative form of && but runs regardless */
2229 /* If finishing off a redirect, add a whitespace delimiter */
2230 if (curCopyTo == curRedirs) {
2231 curCopyTo[(*curLen)++] = ' ';
2234 /* If a redirect in place, it ends here */
2235 curCopyTo = curString;
2236 curLen = &curStringLen;
2237 curCopyTo[(*curLen)++] = *curPos;
2238 lastWasRedirect = FALSE;
2240 } else if (inQuotes) {
2241 curCopyTo[(*curLen)++] = *curPos;
2242 lastWasRedirect = FALSE;
2244 } else {
2245 /* Make a redirect start here */
2246 curCopyTo = curRedirs;
2247 curLen = &curRedirsLen;
2248 curCopyTo[(*curLen)++] = *curPos;
2249 lastWasRedirect = TRUE;
2251 break;
2254 case '"': inQuotes = !inQuotes;
2255 curCopyTo[(*curLen)++] = *curPos;
2256 lastWasRedirect = FALSE;
2257 break;
2259 case '(': /* If a '(' is the first non whitespace in a command portion
2260 ie start of line or just after &&, then we read until an
2261 unquoted ) is found */
2262 WINE_TRACE("Found '(' conditions: curLen(%d), inQ(%d), onlyWS(%d)"
2263 ", for(%d, In:%d, Do:%d)"
2264 ", if(%d, else:%d, lwe:%d)\n",
2265 *curLen, inQuotes,
2266 onlyWhiteSpace,
2267 inFor, lastWasIn, lastWasDo,
2268 inIf, inElse, lastWasElse);
2269 lastWasRedirect = FALSE;
2271 /* Ignore open brackets inside the for set */
2272 if (*curLen == 0 && !inIn) {
2273 curDepth++;
2275 /* If in quotes, ignore brackets */
2276 } else if (inQuotes) {
2277 curCopyTo[(*curLen)++] = *curPos;
2279 /* In a FOR loop, an unquoted '(' may occur straight after
2280 IN or DO
2281 In an IF statement just handle it regardless as we don't
2282 parse the operands
2283 In an ELSE statement, only allow it straight away after
2284 the ELSE and whitespace
2286 } else if (inIf ||
2287 (inElse && lastWasElse && onlyWhiteSpace) ||
2288 (inFor && (lastWasIn || lastWasDo) && onlyWhiteSpace)) {
2290 /* If entering into an 'IN', set inIn */
2291 if (inFor && lastWasIn && onlyWhiteSpace) {
2292 WINE_TRACE("Inside an IN\n");
2293 inIn = TRUE;
2296 /* Add the current command */
2297 WCMD_addCommand(curString, &curStringLen,
2298 curRedirs, &curRedirsLen,
2299 &curCopyTo, &curLen,
2300 isAmphersand, curDepth,
2301 &lastEntry, output);
2303 curDepth++;
2304 } else {
2305 curCopyTo[(*curLen)++] = *curPos;
2307 break;
2309 case '&': if (!inQuotes && *(curPos+1) == '&') {
2310 curPos++; /* Skip other & */
2311 lastWasRedirect = FALSE;
2313 /* Add an entry to the command list */
2314 if (curStringLen > 0) {
2316 /* Add the current command */
2317 WCMD_addCommand(curString, &curStringLen,
2318 curRedirs, &curRedirsLen,
2319 &curCopyTo, &curLen,
2320 isAmphersand, curDepth,
2321 &lastEntry, output);
2324 isAmphersand = TRUE;
2325 } else {
2326 curCopyTo[(*curLen)++] = *curPos;
2328 break;
2330 case ')': if (!inQuotes && curDepth > 0) {
2331 lastWasRedirect = FALSE;
2333 /* Add the current command if there is one */
2334 if (curStringLen) {
2336 /* Add the current command */
2337 WCMD_addCommand(curString, &curStringLen,
2338 curRedirs, &curRedirsLen,
2339 &curCopyTo, &curLen,
2340 isAmphersand, curDepth,
2341 &lastEntry, output);
2344 /* Add an empty entry to the command list */
2345 isAmphersand = FALSE;
2346 WCMD_addCommand(NULL, &curStringLen,
2347 curRedirs, &curRedirsLen,
2348 &curCopyTo, &curLen,
2349 isAmphersand, curDepth,
2350 &lastEntry, output);
2351 curDepth--;
2353 /* Leave inIn if necessary */
2354 if (inIn) inIn = FALSE;
2355 } else {
2356 curCopyTo[(*curLen)++] = *curPos;
2358 break;
2359 default:
2360 lastWasRedirect = FALSE;
2361 curCopyTo[(*curLen)++] = *curPos;
2364 curPos++;
2366 /* At various times we need to know if we have only skipped whitespace,
2367 so reset this variable and then it will remain true until a non
2368 whitespace is found */
2369 if ((thisChar != ' ') && (thisChar != '\n')) onlyWhiteSpace = FALSE;
2371 /* Flag end of interest in FOR DO and IN parms once something has been processed */
2372 if (!lastWasWhiteSpace) {
2373 lastWasIn = lastWasDo = FALSE;
2376 /* If we have reached the end, add this command into the list */
2377 if (*curPos == 0x00 && *curLen > 0) {
2379 /* Add an entry to the command list */
2380 WCMD_addCommand(curString, &curStringLen,
2381 curRedirs, &curRedirsLen,
2382 &curCopyTo, &curLen,
2383 isAmphersand, curDepth,
2384 &lastEntry, output);
2387 /* If we have reached the end of the string, see if bracketing outstanding */
2388 if (*curPos == 0x00 && curDepth > 0 && readFrom != INVALID_HANDLE_VALUE) {
2389 inRem = FALSE;
2390 isAmphersand = FALSE;
2391 inQuotes = FALSE;
2392 memset(extraSpace, 0x00, (MAXSTRING+1) * sizeof(WCHAR));
2394 /* Read more, skipping any blank lines */
2395 while (*extraSpace == 0x00) {
2396 if (!context) WCMD_output_asis( WCMD_LoadMessage(WCMD_MOREPROMPT));
2397 if (WCMD_fgets(extraSpace, MAXSTRING, readFrom) == NULL) break;
2399 curPos = extraSpace;
2400 if (context) handleExpansion(extraSpace, FALSE, NULL, NULL);
2404 /* Dump out the parsed output */
2405 WCMD_DumpCommands(*output);
2407 return extraSpace;
2410 /***************************************************************************
2411 * WCMD_process_commands
2413 * Process all the commands read in so far
2415 CMD_LIST *WCMD_process_commands(CMD_LIST *thisCmd, BOOL oneBracket,
2416 WCHAR *var, WCHAR *val) {
2418 int bdepth = -1;
2420 if (thisCmd && oneBracket) bdepth = thisCmd->bracketDepth;
2422 /* Loop through the commands, processing them one by one */
2423 while (thisCmd) {
2425 CMD_LIST *origCmd = thisCmd;
2427 /* If processing one bracket only, and we find the end bracket
2428 entry (or less), return */
2429 if (oneBracket && !thisCmd->command &&
2430 bdepth <= thisCmd->bracketDepth) {
2431 WINE_TRACE("Finished bracket @ %p, next command is %p\n",
2432 thisCmd, thisCmd->nextcommand);
2433 return thisCmd->nextcommand;
2436 /* Ignore the NULL entries a ')' inserts (Only 'if' cares
2437 about them and it will be handled in there)
2438 Also, skip over any batch labels (eg. :fred) */
2439 if (thisCmd->command && thisCmd->command[0] != ':') {
2441 WINE_TRACE("Executing command: '%s'\n", wine_dbgstr_w(thisCmd->command));
2443 if (strchrW(thisCmd->redirects,'|') != NULL) {
2444 WCMD_pipe (&thisCmd, var, val);
2445 } else {
2446 WCMD_execute (thisCmd->command, thisCmd->redirects, var, val, &thisCmd);
2450 /* Step on unless the command itself already stepped on */
2451 if (thisCmd == origCmd) thisCmd = thisCmd->nextcommand;
2453 return NULL;
2456 /***************************************************************************
2457 * WCMD_free_commands
2459 * Frees the storage held for a parsed command line
2460 * - This is not done in the process_commands, as eventually the current
2461 * pointer will be modified within the commands, and hence a single free
2462 * routine is simpler
2464 void WCMD_free_commands(CMD_LIST *cmds) {
2466 /* Loop through the commands, freeing them one by one */
2467 while (cmds) {
2468 CMD_LIST *thisCmd = cmds;
2469 cmds = cmds->nextcommand;
2470 HeapFree(GetProcessHeap(), 0, thisCmd->command);
2471 HeapFree(GetProcessHeap(), 0, thisCmd);