Create the AHCI branch for Aman's work
[reactos.git] / base / shell / cmd / cmd.c
1 /*
2 * CMD.C - command-line interface.
3 *
4 *
5 * History:
6 *
7 * 17 Jun 1994 (Tim Norman)
8 * started.
9 *
10 * 08 Aug 1995 (Matt Rains)
11 * I have cleaned up the source code. changes now bring this source
12 * into guidelines for recommended programming practice.
13 *
14 * A added the the standard FreeDOS GNU licence test to the
15 * initialize() function.
16 *
17 * Started to replace puts() with printf(). this will help
18 * standardize output. please follow my lead.
19 *
20 * I have added some constants to help making changes easier.
21 *
22 * 15 Dec 1995 (Tim Norman)
23 * major rewrite of the code to make it more efficient and add
24 * redirection support (finally!)
25 *
26 * 06 Jan 1996 (Tim Norman)
27 * finished adding redirection support! Changed to use our own
28 * exec code (MUCH thanks to Svante Frey!!)
29 *
30 * 29 Jan 1996 (Tim Norman)
31 * added support for CHDIR, RMDIR, MKDIR, and ERASE, as per
32 * suggestion of Steffan Kaiser
33 *
34 * changed "file not found" error message to "bad command or
35 * filename" thanks to Dustin Norman for noticing that confusing
36 * message!
37 *
38 * changed the format to call internal commands (again) so that if
39 * they want to split their commands, they can do it themselves
40 * (none of the internal functions so far need that much power, anyway)
41 *
42 * 27 Aug 1996 (Tim Norman)
43 * added in support for Oliver Mueller's ALIAS command
44 *
45 * 14 Jun 1997 (Steffan Kaiser)
46 * added ctrl-break handling and error level
47 *
48 * 16 Jun 1998 (Rob Lake)
49 * Runs command.com if /P is specified in command line. Command.com
50 * also stays permanent. If /C is in the command line, starts the
51 * program next in the line.
52 *
53 * 21 Jun 1998 (Rob Lake)
54 * Fixed up /C so that arguments for the program
55 *
56 * 08-Jul-1998 (John P. Price)
57 * Now sets COMSPEC environment variable
58 * misc clean up and optimization
59 * added date and time commands
60 * changed to using spawnl instead of exec. exec does not copy the
61 * environment to the child process!
62 *
63 * 14 Jul 1998 (Hans B Pufal)
64 * Reorganised source to be more efficient and to more closely
65 * follow MS-DOS conventions. (eg %..% environment variable
66 * replacement works form command line as well as batch file.
67 *
68 * New organisation also properly support nested batch files.
69 *
70 * New command table structure is half way towards providing a
71 * system in which COMMAND will find out what internal commands
72 * are loaded
73 *
74 * 24 Jul 1998 (Hans B Pufal) [HBP_003]
75 * Fixed return value when called with /C option
76 *
77 * 27 Jul 1998 John P. Price
78 * added config.h include
79 *
80 * 28 Jul 1998 John P. Price
81 * added showcmds function to show commands and options available
82 *
83 * 07-Aug-1998 (John P Price <linux-guru@gcfl.net>)
84 * Fixed carrage return output to better match MSDOS with echo
85 * on or off. (marked with "JPP 19980708")
86 *
87 * 07-Dec-1998 (Eric Kohl)
88 * First ReactOS release.
89 * Extended length of commandline buffers to 512.
90 *
91 * 13-Dec-1998 (Eric Kohl)
92 * Added COMSPEC environment variable.
93 * Added "/t" support (color) on cmd command line.
94 *
95 * 07-Jan-1999 (Eric Kohl)
96 * Added help text ("cmd /?").
97 *
98 * 25-Jan-1999 (Eric Kohl)
99 * Unicode and redirection safe!
100 * Fixed redirections and piping.
101 * Piping is based on temporary files, but basic support
102 * for anonymous pipes already exists.
103 *
104 * 27-Jan-1999 (Eric Kohl)
105 * Replaced spawnl() by CreateProcess().
106 *
107 * 22-Oct-1999 (Eric Kohl)
108 * Added break handler.
109 *
110 * 15-Dec-1999 (Eric Kohl)
111 * Fixed current directory
112 *
113 * 28-Dec-1999 (Eric Kohl)
114 * Restore window title after program/batch execution
115 *
116 * 03-Feb-2001 (Eric Kohl)
117 * Workaround because argc[0] is NULL under ReactOS
118 *
119 * 23-Feb-2001 (Carl Nettelblad <cnettel@hem.passagen.se>)
120 * %envvar% replacement conflicted with for.
121 *
122 * 30-Apr-2004 (Filip Navara <xnavara@volny.cz>)
123 * Make MakeSureDirectoryPathExistsEx unicode safe.
124 *
125 * 28-Mai-2004
126 * Removed MakeSureDirectoryPathExistsEx.
127 * Use the current directory if GetTempPath fails.
128 *
129 * 12-Jul-2004 (Jens Collin <jens.collin@lakhei.com>)
130 * Added ShellExecute call when all else fails to be able to "launch" any file.
131 *
132 * 02-Apr-2005 (Magnus Olsen <magnus@greatlord.com>)
133 * Remove all hardcode string to En.rc
134 *
135 * 06-May-2005 (Klemens Friedl <frik85@gmail.com>)
136 * Add 'help' command (list all commands plus description)
137 *
138 * 06-jul-2005 (Magnus Olsen <magnus@greatlord.com>)
139 * translate '%errorlevel%' to the internal value.
140 * Add proper memmory alloc ProcessInput, the error
141 * handling for memmory handling need to be improve
142 */
143
144 #include "precomp.h"
145 #include <reactos/buildno.h>
146 #include <reactos/version.h>
147
148 #ifndef NT_SUCCESS
149 #define NT_SUCCESS(StatCode) ((NTSTATUS)(StatCode) >= 0)
150 #endif
151
152 typedef NTSTATUS (WINAPI *NtQueryInformationProcessProc)(HANDLE, PROCESSINFOCLASS,
153 PVOID, ULONG, PULONG);
154 typedef NTSTATUS (WINAPI *NtReadVirtualMemoryProc)(HANDLE, PVOID, PVOID, ULONG, PULONG);
155
156 BOOL bExit = FALSE; /* indicates EXIT was typed */
157 BOOL bCanExit = TRUE; /* indicates if this shell is exitable */
158 BOOL bCtrlBreak = FALSE; /* Ctrl-Break or Ctrl-C hit */
159 BOOL bIgnoreEcho = FALSE; /* Set this to TRUE to prevent a newline, when executing a command */
160 INT nErrorLevel = 0; /* Errorlevel of last launched external program */
161 CRITICAL_SECTION ChildProcessRunningLock;
162 BOOL bUnicodeOutput = FALSE;
163 BOOL bDisableBatchEcho = FALSE;
164 BOOL bDelayedExpansion = FALSE;
165 DWORD dwChildProcessId = 0;
166 HANDLE hIn;
167 HANDLE hOut;
168 LPTSTR lpOriginalEnvironment;
169 HANDLE CMD_ModuleHandle;
170
171 static NtQueryInformationProcessProc NtQueryInformationProcessPtr = NULL;
172 static NtReadVirtualMemoryProc NtReadVirtualMemoryPtr = NULL;
173
174 #ifdef INCLUDE_CMD_COLOR
175 WORD wDefColor; /* default color */
176 #endif
177
178 /*
179 * convert
180 *
181 * insert commas into a number
182 */
183 INT
184 ConvertULargeInteger(ULONGLONG num, LPTSTR des, UINT len, BOOL bPutSeperator)
185 {
186 TCHAR temp[39]; /* maximum length with nNumberGroups == 1 */
187 UINT n, iTarget;
188
189 if (len <= 1)
190 return 0;
191
192 n = 0;
193 iTarget = nNumberGroups;
194 if (!nNumberGroups)
195 bPutSeperator = FALSE;
196
197 do
198 {
199 if (iTarget == n && bPutSeperator)
200 {
201 iTarget += nNumberGroups + 1;
202 temp[38 - n++] = cThousandSeparator;
203 }
204 temp[38 - n++] = (TCHAR)(num % 10) + _T('0');
205 num /= 10;
206 } while (num > 0);
207 if (n > len-1)
208 n = len-1;
209
210 memcpy(des, temp + 39 - n, n * sizeof(TCHAR));
211 des[n] = _T('\0');
212
213 return n;
214 }
215
216 /*
217 * Is a process a console process?
218 */
219 static BOOL IsConsoleProcess(HANDLE Process)
220 {
221 NTSTATUS Status;
222 PROCESS_BASIC_INFORMATION Info;
223 PEB ProcessPeb;
224 ULONG BytesRead;
225
226 if (NULL == NtQueryInformationProcessPtr || NULL == NtReadVirtualMemoryPtr)
227 {
228 return TRUE;
229 }
230
231 Status = NtQueryInformationProcessPtr (
232 Process, ProcessBasicInformation,
233 &Info, sizeof(PROCESS_BASIC_INFORMATION), NULL);
234 if (! NT_SUCCESS(Status))
235 {
236 WARN ("NtQueryInformationProcess failed with status %08x\n", Status);
237 return TRUE;
238 }
239 Status = NtReadVirtualMemoryPtr (
240 Process, Info.PebBaseAddress, &ProcessPeb,
241 sizeof(PEB), &BytesRead);
242 if (! NT_SUCCESS(Status) || sizeof(PEB) != BytesRead)
243 {
244 WARN ("Couldn't read virt mem status %08x bytes read %lu\n", Status, BytesRead);
245 return TRUE;
246 }
247
248 return IMAGE_SUBSYSTEM_WINDOWS_CUI == ProcessPeb.ImageSubsystem;
249 }
250
251
252
253 #ifdef _UNICODE
254 #define SHELLEXECUTETEXT "ShellExecuteExW"
255 #else
256 #define SHELLEXECUTETEXT "ShellExecuteExA"
257 #endif
258
259 typedef BOOL (WINAPI *MYEX)(LPSHELLEXECUTEINFO lpExecInfo);
260
261 HANDLE RunFile(DWORD flags, LPTSTR filename, LPTSTR params,
262 LPTSTR directory, INT show)
263 {
264 SHELLEXECUTEINFO sei;
265 HMODULE hShell32;
266 MYEX hShExt;
267 BOOL ret;
268
269 TRACE ("RunFile(%s)\n", debugstr_aw(filename));
270 hShell32 = LoadLibrary(_T("SHELL32.DLL"));
271 if (!hShell32)
272 {
273 WARN ("RunFile: couldn't load SHELL32.DLL!\n");
274 return NULL;
275 }
276
277 hShExt = (MYEX)(FARPROC)GetProcAddress(hShell32, SHELLEXECUTETEXT);
278 if (!hShExt)
279 {
280 WARN ("RunFile: couldn't find ShellExecuteExA/W in SHELL32.DLL!\n");
281 FreeLibrary(hShell32);
282 return NULL;
283 }
284
285 TRACE ("RunFile: ShellExecuteExA/W is at %x\n", hShExt);
286
287 memset(&sei, 0, sizeof sei);
288 sei.cbSize = sizeof sei;
289 sei.fMask = flags;
290 sei.lpFile = filename;
291 sei.lpParameters = params;
292 sei.lpDirectory = directory;
293 sei.nShow = show;
294 ret = hShExt(&sei);
295
296 TRACE ("RunFile: ShellExecuteExA/W returned 0x%p\n", ret);
297
298 FreeLibrary(hShell32);
299 return ret ? sei.hProcess : NULL;
300 }
301
302
303
304 /*
305 * This command (in first) was not found in the command table
306 *
307 * Full - buffer to hold whole command line
308 * First - first word on command line
309 * Rest - rest of command line
310 */
311 static INT
312 Execute(LPTSTR Full, LPTSTR First, LPTSTR Rest, PARSED_COMMAND *Cmd)
313 {
314 TCHAR szFullName[MAX_PATH];
315 TCHAR *first, *rest, *dot;
316 TCHAR szWindowTitle[MAX_PATH];
317 DWORD dwExitCode = 0;
318 TCHAR *FirstEnd;
319 TCHAR szFullCmdLine [CMDLINE_LENGTH];
320
321 TRACE ("Execute: \'%s\' \'%s\'\n", debugstr_aw(First), debugstr_aw(Rest));
322
323 /* Though it was already parsed once, we have a different set of rules
324 for parsing before we pass to CreateProccess */
325 if (First[0] == _T('/') || (First[0] && First[1] == _T(':')))
326 {
327 /* Use the entire first word as the program name (no change) */
328 FirstEnd = First + _tcslen(First);
329 }
330 else
331 {
332 /* If present in the first word, spaces and ,;=/ end the program
333 * name and become the beginning of its parameters. */
334 BOOL bInside = FALSE;
335 for (FirstEnd = First; *FirstEnd; FirstEnd++)
336 {
337 if (!bInside && (_istspace(*FirstEnd) || _tcschr(_T(",;=/"), *FirstEnd)))
338 break;
339 bInside ^= *FirstEnd == _T('"');
340 }
341 }
342
343 /* Copy the new first/rest into the buffer */
344 first = Full;
345 rest = &Full[FirstEnd - First + 1];
346 _tcscpy(rest, FirstEnd);
347 _tcscat(rest, Rest);
348 *FirstEnd = _T('\0');
349 _tcscpy(first, First);
350
351 /* check for a drive change */
352 if ((_istalpha (first[0])) && (!_tcscmp (first + 1, _T(":"))))
353 {
354 BOOL working = TRUE;
355 if (!SetCurrentDirectory(first))
356 /* Guess they changed disc or something, handle that gracefully and get to root */
357 {
358 TCHAR str[4];
359 str[0]=first[0];
360 str[1]=_T(':');
361 str[2]=_T('\\');
362 str[3]=0;
363 working = SetCurrentDirectory(str);
364 }
365
366 if (!working) ConErrResPuts (STRING_FREE_ERROR1);
367 return !working;
368 }
369
370 /* get the PATH environment variable and parse it */
371 /* search the PATH environment variable for the binary */
372 StripQuotes(First);
373 if (!SearchForExecutable(First, szFullName))
374 {
375 error_bad_command(first);
376 return 1;
377 }
378
379 GetConsoleTitle (szWindowTitle, MAX_PATH);
380
381 /* check if this is a .BAT or .CMD file */
382 dot = _tcsrchr (szFullName, _T('.'));
383 if (dot && (!_tcsicmp (dot, _T(".bat")) || !_tcsicmp (dot, _T(".cmd"))))
384 {
385 while (*rest == _T(' '))
386 rest++;
387 TRACE ("[BATCH: %s %s]\n", debugstr_aw(szFullName), debugstr_aw(rest));
388 dwExitCode = Batch(szFullName, first, rest, Cmd);
389 }
390 else
391 {
392 /* exec the program */
393 PROCESS_INFORMATION prci;
394 STARTUPINFO stui;
395
396 /* build command line for CreateProcess(): FullName + " " + rest */
397 BOOL quoted = !!_tcschr(First, ' ');
398 _tcscpy(szFullCmdLine, quoted ? _T("\"") : _T(""));
399 _tcsncat(szFullCmdLine, First, CMDLINE_LENGTH - _tcslen(szFullCmdLine) - 1);
400 _tcsncat(szFullCmdLine, quoted ? _T("\"") : _T(""), CMDLINE_LENGTH - _tcslen(szFullCmdLine) - 1);
401
402 if (*rest)
403 {
404 _tcsncat(szFullCmdLine, _T(" "), CMDLINE_LENGTH - _tcslen(szFullCmdLine) - 1);
405 _tcsncat(szFullCmdLine, rest, CMDLINE_LENGTH - _tcslen(szFullCmdLine) - 1);
406 }
407
408 TRACE ("[EXEC: %s]\n", debugstr_aw(szFullCmdLine));
409
410 /* fill startup info */
411 memset (&stui, 0, sizeof (STARTUPINFO));
412 stui.cb = sizeof (STARTUPINFO);
413 stui.dwFlags = STARTF_USESHOWWINDOW;
414 stui.wShowWindow = SW_SHOWDEFAULT;
415
416 /* Set the console to standard mode */
417 SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE),
418 ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT);
419
420 if (CreateProcess(szFullName,
421 szFullCmdLine,
422 NULL,
423 NULL,
424 TRUE,
425 0, /* CREATE_NEW_PROCESS_GROUP */
426 NULL,
427 NULL,
428 &stui,
429 &prci))
430 {
431 CloseHandle(prci.hThread);
432 }
433 else
434 {
435 // See if we can run this with ShellExecute() ie myfile.xls
436 prci.hProcess = RunFile(SEE_MASK_NOCLOSEPROCESS | SEE_MASK_NO_CONSOLE,
437 szFullName,
438 rest,
439 NULL,
440 SW_SHOWNORMAL);
441 }
442
443 if (prci.hProcess != NULL)
444 {
445 if (IsConsoleProcess(prci.hProcess))
446 {
447 EnterCriticalSection(&ChildProcessRunningLock);
448 dwChildProcessId = prci.dwProcessId;
449
450 WaitForSingleObject(prci.hProcess, INFINITE);
451
452 LeaveCriticalSection(&ChildProcessRunningLock);
453
454 GetExitCodeProcess(prci.hProcess, &dwExitCode);
455 nErrorLevel = (INT)dwExitCode;
456 }
457 CloseHandle(prci.hProcess);
458 }
459 else
460 {
461 TRACE ("[ShellExecute failed!: %s]\n", debugstr_aw(Full));
462 error_bad_command(first);
463 dwExitCode = 1;
464 }
465
466 /* Restore our default console mode */
467 SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE),
468 ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT);
469 SetConsoleMode(GetStdHandle(STD_OUTPUT_HANDLE),
470 ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
471 }
472
473 /* Get code page if it has been changed */
474 InputCodePage= GetConsoleCP();
475 OutputCodePage = GetConsoleOutputCP();
476 SetConsoleTitle(szWindowTitle);
477
478 return dwExitCode;
479 }
480
481
482 /*
483 * look through the internal commands and determine whether or not this
484 * command is one of them. If it is, call the command. If not, call
485 * execute to run it as an external program.
486 *
487 * first - first word on command line
488 * rest - rest of command line
489 */
490 INT
491 DoCommand(LPTSTR first, LPTSTR rest, PARSED_COMMAND *Cmd)
492 {
493 TCHAR *com;
494 TCHAR *cp;
495 LPTSTR param; /* pointer to command's parameters */
496 INT cl;
497 LPCOMMAND cmdptr;
498 BOOL nointernal = FALSE;
499 INT ret;
500
501 TRACE ("DoCommand: (\'%s\' \'%s\')\n", debugstr_aw(first), debugstr_aw(rest));
502
503 /* full command line */
504 com = cmd_alloc((_tcslen(first) + _tcslen(rest) + 2) * sizeof(TCHAR));
505 if (com == NULL)
506 {
507 error_out_of_memory();
508 return 1;
509 }
510
511 /* If present in the first word, these characters end the name of an
512 * internal command and become the beginning of its parameters. */
513 cp = first + _tcscspn(first, _T("\t +,/;=[]"));
514
515 for (cl = 0; cl < (cp - first); cl++)
516 {
517 /* These characters do it too, but if one of them is present,
518 * then we check to see if the word is a file name and skip
519 * checking for internal commands if so.
520 * This allows running programs with names like "echo.exe" */
521 if (_tcschr(_T(".:\\"), first[cl]))
522 {
523 TCHAR tmp = *cp;
524 *cp = _T('\0');
525 nointernal = IsExistingFile(first);
526 *cp = tmp;
527 break;
528 }
529 }
530
531 /* Scan internal command table */
532 for (cmdptr = cmds; !nointernal && cmdptr->name; cmdptr++)
533 {
534 if (!_tcsnicmp(first, cmdptr->name, cl) && cmdptr->name[cl] == _T('\0'))
535 {
536 _tcscpy(com, first);
537 _tcscat(com, rest);
538 param = &com[cl];
539
540 /* Skip over whitespace to rest of line, exclude 'echo' command */
541 if (_tcsicmp(cmdptr->name, _T("echo")) != 0)
542 while (_istspace(*param))
543 param++;
544 ret = cmdptr->func(param);
545 cmd_free(com);
546 return ret;
547 }
548 }
549
550 ret = Execute(com, first, rest, Cmd);
551 cmd_free(com);
552 return ret;
553 }
554
555
556 /*
557 * process the command line and execute the appropriate functions
558 * full input/output redirection and piping are supported
559 */
560 INT ParseCommandLine (LPTSTR cmd)
561 {
562 INT Ret = 0;
563 PARSED_COMMAND *Cmd = ParseCommand(cmd);
564 if (Cmd)
565 {
566 Ret = ExecuteCommand(Cmd);
567 FreeCommand(Cmd);
568 }
569 return Ret;
570 }
571
572 /* Execute a command without waiting for it to finish. If it's an internal
573 * command or batch file, we must create a new cmd.exe process to handle it.
574 * TODO: For now, this just always creates a cmd.exe process.
575 * This works, but is inefficient for running external programs,
576 * which could just be run directly. */
577 static HANDLE
578 ExecuteAsync(PARSED_COMMAND *Cmd)
579 {
580 TCHAR CmdPath[MAX_PATH];
581 TCHAR CmdParams[CMDLINE_LENGTH], *ParamsEnd;
582 STARTUPINFO stui;
583 PROCESS_INFORMATION prci;
584
585 /* Get the path to cmd.exe */
586 GetModuleFileName(NULL, CmdPath, MAX_PATH);
587
588 /* Build the parameter string to pass to cmd.exe */
589 ParamsEnd = _stpcpy(CmdParams, _T("/S/D/C\""));
590 ParamsEnd = Unparse(Cmd, ParamsEnd, &CmdParams[CMDLINE_LENGTH - 2]);
591 if (!ParamsEnd)
592 {
593 error_out_of_memory();
594 return NULL;
595 }
596 _tcscpy(ParamsEnd, _T("\""));
597
598 memset(&stui, 0, sizeof stui);
599 stui.cb = sizeof(STARTUPINFO);
600 if (!CreateProcess(CmdPath, CmdParams, NULL, NULL, TRUE, 0,
601 NULL, NULL, &stui, &prci))
602 {
603 ErrorMessage(GetLastError(), NULL);
604 return NULL;
605 }
606
607 CloseHandle(prci.hThread);
608 return prci.hProcess;
609 }
610
611 static VOID
612 ExecutePipeline(PARSED_COMMAND *Cmd)
613 {
614 #ifdef FEATURE_REDIRECTION
615 HANDLE hInput = NULL;
616 HANDLE hOldConIn = GetStdHandle(STD_INPUT_HANDLE);
617 HANDLE hOldConOut = GetStdHandle(STD_OUTPUT_HANDLE);
618 HANDLE hProcess[MAXIMUM_WAIT_OBJECTS];
619 INT nProcesses = 0;
620 DWORD dwExitCode;
621
622 /* Do all but the last pipe command */
623 do
624 {
625 HANDLE hPipeRead, hPipeWrite;
626 if (nProcesses > (MAXIMUM_WAIT_OBJECTS - 2))
627 {
628 error_too_many_parameters(_T("|"));
629 goto failed;
630 }
631
632 /* Create the pipe that this process will write into.
633 * Make the handles non-inheritable initially, because this
634 * process shouldn't inherit the reading handle. */
635 if (!CreatePipe(&hPipeRead, &hPipeWrite, NULL, 0))
636 {
637 error_no_pipe();
638 goto failed;
639 }
640
641 /* The writing side of the pipe is STDOUT for this process */
642 SetHandleInformation(hPipeWrite, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT);
643 SetStdHandle(STD_OUTPUT_HANDLE, hPipeWrite);
644
645 /* Execute it (error check is done later for easier cleanup) */
646 hProcess[nProcesses] = ExecuteAsync(Cmd->Subcommands);
647 CloseHandle(hPipeWrite);
648 if (hInput)
649 CloseHandle(hInput);
650
651 /* The reading side of the pipe will be STDIN for the next process */
652 SetHandleInformation(hPipeRead, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT);
653 SetStdHandle(STD_INPUT_HANDLE, hPipeRead);
654 hInput = hPipeRead;
655
656 if (!hProcess[nProcesses])
657 goto failed;
658 nProcesses++;
659
660 Cmd = Cmd->Subcommands->Next;
661 } while (Cmd->Type == C_PIPE);
662
663 /* The last process uses the original STDOUT */
664 SetStdHandle(STD_OUTPUT_HANDLE, hOldConOut);
665 hProcess[nProcesses] = ExecuteAsync(Cmd);
666 if (!hProcess[nProcesses])
667 goto failed;
668 nProcesses++;
669 CloseHandle(hInput);
670 SetStdHandle(STD_INPUT_HANDLE, hOldConIn);
671
672 /* Wait for all processes to complete */
673 EnterCriticalSection(&ChildProcessRunningLock);
674 WaitForMultipleObjects(nProcesses, hProcess, TRUE, INFINITE);
675 LeaveCriticalSection(&ChildProcessRunningLock);
676
677 /* Use the exit code of the last process in the pipeline */
678 GetExitCodeProcess(hProcess[nProcesses - 1], &dwExitCode);
679 nErrorLevel = (INT)dwExitCode;
680
681 while (--nProcesses >= 0)
682 CloseHandle(hProcess[nProcesses]);
683 return;
684
685 failed:
686 if (hInput)
687 CloseHandle(hInput);
688 while (--nProcesses >= 0)
689 {
690 TerminateProcess(hProcess[nProcesses], 0);
691 CloseHandle(hProcess[nProcesses]);
692 }
693 SetStdHandle(STD_INPUT_HANDLE, hOldConIn);
694 SetStdHandle(STD_OUTPUT_HANDLE, hOldConOut);
695 #endif
696 }
697
698 INT
699 ExecuteCommand(PARSED_COMMAND *Cmd)
700 {
701 PARSED_COMMAND *Sub;
702 LPTSTR First, Rest;
703 INT Ret = 0;
704
705 if (!PerformRedirection(Cmd->Redirections))
706 return 1;
707
708 switch (Cmd->Type)
709 {
710 case C_COMMAND:
711 Ret = 1;
712 First = DoDelayedExpansion(Cmd->Command.First);
713 if (First)
714 {
715 Rest = DoDelayedExpansion(Cmd->Command.Rest);
716 if (Rest)
717 {
718 Ret = DoCommand(First, Rest, Cmd);
719 cmd_free(Rest);
720 }
721 cmd_free(First);
722 }
723 break;
724 case C_QUIET:
725 case C_BLOCK:
726 case C_MULTI:
727 for (Sub = Cmd->Subcommands; Sub; Sub = Sub->Next)
728 Ret = ExecuteCommand(Sub);
729 break;
730 case C_IFFAILURE:
731 Sub = Cmd->Subcommands;
732 Ret = ExecuteCommand(Sub);
733 if (Ret != 0)
734 {
735 nErrorLevel = Ret;
736 Ret = ExecuteCommand(Sub->Next);
737 }
738 break;
739 case C_IFSUCCESS:
740 Sub = Cmd->Subcommands;
741 Ret = ExecuteCommand(Sub);
742 if (Ret == 0)
743 Ret = ExecuteCommand(Sub->Next);
744 break;
745 case C_PIPE:
746 ExecutePipeline(Cmd);
747 break;
748 case C_IF:
749 Ret = ExecuteIf(Cmd);
750 break;
751 case C_FOR:
752 Ret = ExecuteFor(Cmd);
753 break;
754 }
755
756 UndoRedirection(Cmd->Redirections, NULL);
757 return Ret;
758 }
759
760 LPTSTR
761 GetEnvVar(LPCTSTR varName)
762 {
763 static LPTSTR ret = NULL;
764 UINT size;
765
766 cmd_free(ret);
767 ret = NULL;
768 size = GetEnvironmentVariable(varName, NULL, 0);
769 if (size > 0)
770 {
771 ret = cmd_alloc(size * sizeof(TCHAR));
772 if (ret != NULL)
773 GetEnvironmentVariable(varName, ret, size + 1);
774 }
775 return ret;
776 }
777
778 LPCTSTR
779 GetEnvVarOrSpecial(LPCTSTR varName)
780 {
781 static TCHAR ret[MAX_PATH];
782
783 LPTSTR var = GetEnvVar(varName);
784 if (var)
785 return var;
786
787 /* env var doesn't exist, look for a "special" one */
788 /* %CD% */
789 if (_tcsicmp(varName,_T("cd")) ==0)
790 {
791 GetCurrentDirectory(MAX_PATH, ret);
792 return ret;
793 }
794 /* %TIME% */
795 else if (_tcsicmp(varName,_T("time")) ==0)
796 {
797 return GetTimeString();
798 }
799 /* %DATE% */
800 else if (_tcsicmp(varName,_T("date")) ==0)
801 {
802 return GetDateString();
803 }
804
805 /* %RANDOM% */
806 else if (_tcsicmp(varName,_T("random")) ==0)
807 {
808 /* Get random number */
809 _itot(rand(),ret,10);
810 return ret;
811 }
812
813 /* %CMDCMDLINE% */
814 else if (_tcsicmp(varName,_T("cmdcmdline")) ==0)
815 {
816 return GetCommandLine();
817 }
818
819 /* %CMDEXTVERSION% */
820 else if (_tcsicmp(varName,_T("cmdextversion")) ==0)
821 {
822 /* Set version number to 2 */
823 _itot(2,ret,10);
824 return ret;
825 }
826
827 /* %ERRORLEVEL% */
828 else if (_tcsicmp(varName,_T("errorlevel")) ==0)
829 {
830 _itot(nErrorLevel,ret,10);
831 return ret;
832 }
833
834 return NULL;
835 }
836
837 /* Handle the %~var syntax */
838 static LPTSTR
839 GetEnhancedVar(TCHAR **pFormat, LPTSTR (*GetVar)(TCHAR, BOOL *))
840 {
841 static const TCHAR ModifierTable[] = _T("dpnxfsatz");
842 enum {
843 M_DRIVE = 1, /* D: drive letter */
844 M_PATH = 2, /* P: path */
845 M_NAME = 4, /* N: filename */
846 M_EXT = 8, /* X: extension */
847 M_FULL = 16, /* F: full path (drive+path+name+ext) */
848 M_SHORT = 32, /* S: full path (drive+path+name+ext), use short names */
849 M_ATTR = 64, /* A: attributes */
850 M_TIME = 128, /* T: modification time */
851 M_SIZE = 256, /* Z: file size */
852 } Modifiers = 0;
853
854 TCHAR *Format, *FormatEnd;
855 TCHAR *PathVarName = NULL;
856 LPTSTR Variable;
857 TCHAR *VarEnd;
858 BOOL VariableIsParam0;
859 TCHAR FullPath[MAX_PATH];
860 TCHAR FixedPath[MAX_PATH], *Filename, *Extension;
861 HANDLE hFind;
862 WIN32_FIND_DATA w32fd;
863 TCHAR *In, *Out;
864
865 static TCHAR Result[CMDLINE_LENGTH];
866
867 /* There is ambiguity between modifier characters and FOR variables;
868 * the rule that cmd uses is to pick the longest possible match.
869 * For example, if there is a %n variable, then out of %~anxnd,
870 * %~anxn will be substituted rather than just %~an. */
871
872 /* First, go through as many modifier characters as possible */
873 FormatEnd = Format = *pFormat;
874 while (*FormatEnd && _tcschr(ModifierTable, _totlower(*FormatEnd)))
875 FormatEnd++;
876
877 if (*FormatEnd == _T('$'))
878 {
879 /* $PATH: syntax */
880 PathVarName = FormatEnd + 1;
881 FormatEnd = _tcschr(PathVarName, _T(':'));
882 if (!FormatEnd)
883 return NULL;
884
885 /* Must be immediately followed by the variable */
886 Variable = GetVar(*++FormatEnd, &VariableIsParam0);
887 if (!Variable)
888 return NULL;
889 }
890 else
891 {
892 /* Backtrack if necessary to get a variable name match */
893 while (!(Variable = GetVar(*FormatEnd, &VariableIsParam0)))
894 {
895 if (FormatEnd == Format)
896 return NULL;
897 FormatEnd--;
898 }
899 }
900
901 for (; Format < FormatEnd && *Format != _T('$'); Format++)
902 Modifiers |= 1 << (_tcschr(ModifierTable, _totlower(*Format)) - ModifierTable);
903
904 *pFormat = FormatEnd + 1;
905
906 /* Exclude the leading and trailing quotes */
907 VarEnd = &Variable[_tcslen(Variable)];
908 if (*Variable == _T('"'))
909 {
910 Variable++;
911 if (VarEnd > Variable && VarEnd[-1] == _T('"'))
912 VarEnd--;
913 }
914
915 if ((char *)VarEnd - (char *)Variable >= sizeof Result)
916 return _T("");
917 memcpy(Result, Variable, (char *)VarEnd - (char *)Variable);
918 Result[VarEnd - Variable] = _T('\0');
919
920 if (PathVarName)
921 {
922 /* $PATH: syntax - search the directories listed in the
923 * specified environment variable for the file */
924 LPTSTR PathVar;
925 FormatEnd[-1] = _T('\0');
926 PathVar = GetEnvVar(PathVarName);
927 FormatEnd[-1] = _T(':');
928 if (!PathVar ||
929 !SearchPath(PathVar, Result, NULL, MAX_PATH, FullPath, NULL))
930 {
931 return _T("");
932 }
933 }
934 else if (Modifiers == 0)
935 {
936 /* For plain %~var with no modifiers, just return the variable without quotes */
937 return Result;
938 }
939 else if (VariableIsParam0)
940 {
941 /* Special case: If the variable is %0 and modifier characters are present,
942 * use the batch file's path (which includes the .bat/.cmd extension)
943 * rather than the actual %0 variable (which might not). */
944 _tcscpy(FullPath, bc->BatchFilePath);
945 }
946 else
947 {
948 /* Convert the variable, now without quotes, to a full path */
949 if (!GetFullPathName(Result, MAX_PATH, FullPath, NULL))
950 return _T("");
951 }
952
953 /* Next step is to change the path to fix letter case (e.g.
954 * C:\ReAcToS -> C:\ReactOS) and, if requested with the S modifier,
955 * replace long filenames with short. */
956
957 In = FullPath;
958 Out = FixedPath;
959
960 /* Copy drive letter */
961 *Out++ = *In++;
962 *Out++ = *In++;
963 *Out++ = *In++;
964 /* Loop over each \-separated component in the path */
965 do {
966 TCHAR *Next = _tcschr(In, _T('\\'));
967 if (Next)
968 *Next++ = _T('\0');
969 /* Use FindFirstFile to get the correct name */
970 if (Out + _tcslen(In) + 1 >= &FixedPath[MAX_PATH])
971 return _T("");
972 _tcscpy(Out, In);
973 hFind = FindFirstFile(FixedPath, &w32fd);
974 /* If it doesn't exist, just leave the name as it was given */
975 if (hFind != INVALID_HANDLE_VALUE)
976 {
977 LPTSTR FixedComponent = w32fd.cFileName;
978 if (*w32fd.cAlternateFileName &&
979 ((Modifiers & M_SHORT) || !_tcsicmp(In, w32fd.cAlternateFileName)))
980 {
981 FixedComponent = w32fd.cAlternateFileName;
982 }
983 FindClose(hFind);
984
985 if (Out + _tcslen(FixedComponent) + 1 >= &FixedPath[MAX_PATH])
986 return _T("");
987 _tcscpy(Out, FixedComponent);
988 }
989 Filename = Out;
990 Out += _tcslen(Out);
991 *Out++ = _T('\\');
992
993 In = Next;
994 } while (In != NULL);
995 Out[-1] = _T('\0');
996
997 /* Build the result string. Start with attributes, modification time, and
998 * file size. If the file didn't exist, these fields will all be empty. */
999 Out = Result;
1000 if (hFind != INVALID_HANDLE_VALUE)
1001 {
1002 if (Modifiers & M_ATTR)
1003 {
1004 static const struct {
1005 TCHAR Character;
1006 WORD Value;
1007 } *Attrib, Table[] = {
1008 { _T('d'), FILE_ATTRIBUTE_DIRECTORY },
1009 { _T('r'), FILE_ATTRIBUTE_READONLY },
1010 { _T('a'), FILE_ATTRIBUTE_ARCHIVE },
1011 { _T('h'), FILE_ATTRIBUTE_HIDDEN },
1012 { _T('s'), FILE_ATTRIBUTE_SYSTEM },
1013 { _T('c'), FILE_ATTRIBUTE_COMPRESSED },
1014 { _T('o'), FILE_ATTRIBUTE_OFFLINE },
1015 { _T('t'), FILE_ATTRIBUTE_TEMPORARY },
1016 { _T('l'), FILE_ATTRIBUTE_REPARSE_POINT },
1017 };
1018 for (Attrib = Table; Attrib != &Table[9]; Attrib++)
1019 {
1020 *Out++ = w32fd.dwFileAttributes & Attrib->Value
1021 ? Attrib->Character
1022 : _T('-');
1023 }
1024 *Out++ = _T(' ');
1025 }
1026 if (Modifiers & M_TIME)
1027 {
1028 FILETIME ft;
1029 SYSTEMTIME st;
1030 FileTimeToLocalFileTime(&w32fd.ftLastWriteTime, &ft);
1031 FileTimeToSystemTime(&ft, &st);
1032
1033 Out += FormatDate(Out, &st, TRUE);
1034 *Out++ = _T(' ');
1035 Out += FormatTime(Out, &st);
1036 *Out++ = _T(' ');
1037 }
1038 if (Modifiers & M_SIZE)
1039 {
1040 ULARGE_INTEGER Size;
1041 Size.LowPart = w32fd.nFileSizeLow;
1042 Size.HighPart = w32fd.nFileSizeHigh;
1043 Out += _stprintf(Out, _T("%I64u "), Size.QuadPart);
1044 }
1045 }
1046
1047 /* When using the path-searching syntax or the S modifier,
1048 * at least part of the file path is always included.
1049 * If none of the DPNX modifiers are present, include the full path */
1050 if (PathVarName || (Modifiers & M_SHORT))
1051 if ((Modifiers & (M_DRIVE | M_PATH | M_NAME | M_EXT)) == 0)
1052 Modifiers |= M_FULL;
1053
1054 /* Now add the requested parts of the name.
1055 * With the F modifier, add all parts to form the full path. */
1056 Extension = _tcsrchr(Filename, _T('.'));
1057 if (Modifiers & (M_DRIVE | M_FULL))
1058 {
1059 *Out++ = FixedPath[0];
1060 *Out++ = FixedPath[1];
1061 }
1062 if (Modifiers & (M_PATH | M_FULL))
1063 {
1064 memcpy(Out, &FixedPath[2], (char *)Filename - (char *)&FixedPath[2]);
1065 Out += Filename - &FixedPath[2];
1066 }
1067 if (Modifiers & (M_NAME | M_FULL))
1068 {
1069 while (*Filename && Filename != Extension)
1070 *Out++ = *Filename++;
1071 }
1072 if (Modifiers & (M_EXT | M_FULL))
1073 {
1074 if (Extension)
1075 Out = _stpcpy(Out, Extension);
1076 }
1077
1078 /* Trim trailing space which otherwise would appear as a
1079 * result of using the A/T/Z modifiers but no others. */
1080 while (Out != &Result[0] && Out[-1] == _T(' '))
1081 Out--;
1082 *Out = _T('\0');
1083
1084 return Result;
1085 }
1086
1087 LPCTSTR
1088 GetBatchVar(TCHAR *varName, UINT *varNameLen)
1089 {
1090 LPCTSTR ret;
1091 TCHAR *varNameEnd;
1092 BOOL dummy;
1093
1094 *varNameLen = 1;
1095
1096 switch ( *varName )
1097 {
1098 case _T('~'):
1099 varNameEnd = varName + 1;
1100 ret = GetEnhancedVar(&varNameEnd, FindArg);
1101 if (!ret)
1102 {
1103 error_syntax(varName);
1104 return NULL;
1105 }
1106 *varNameLen = varNameEnd - varName;
1107 return ret;
1108 case _T('0'):
1109 case _T('1'):
1110 case _T('2'):
1111 case _T('3'):
1112 case _T('4'):
1113 case _T('5'):
1114 case _T('6'):
1115 case _T('7'):
1116 case _T('8'):
1117 case _T('9'):
1118 return FindArg(*varName, &dummy);
1119
1120 case _T('*'):
1121 //
1122 // Copy over the raw params(not including the batch file name
1123 //
1124 return bc->raw_params;
1125
1126 case _T('%'):
1127 return _T("%");
1128 }
1129 return NULL;
1130 }
1131
1132 BOOL
1133 SubstituteVars(TCHAR *Src, TCHAR *Dest, TCHAR Delim)
1134 {
1135 #define APPEND(From, Length) { \
1136 if (Dest + (Length) > DestEnd) \
1137 goto too_long; \
1138 memcpy(Dest, From, (Length) * sizeof(TCHAR)); \
1139 Dest += Length; }
1140 #define APPEND1(Char) { \
1141 if (Dest >= DestEnd) \
1142 goto too_long; \
1143 *Dest++ = Char; }
1144
1145 TCHAR *DestEnd = Dest + CMDLINE_LENGTH - 1;
1146 const TCHAR *Var;
1147 int VarLength;
1148 TCHAR *SubstStart;
1149 TCHAR EndChr;
1150 while (*Src)
1151 {
1152 if (*Src != Delim)
1153 {
1154 APPEND1(*Src++)
1155 continue;
1156 }
1157
1158 Src++;
1159 if (bc && Delim == _T('%'))
1160 {
1161 UINT NameLen;
1162 Var = GetBatchVar(Src, &NameLen);
1163 if (Var != NULL)
1164 {
1165 VarLength = _tcslen(Var);
1166 APPEND(Var, VarLength)
1167 Src += NameLen;
1168 continue;
1169 }
1170 }
1171
1172 /* Find the end of the variable name. A colon (:) will usually
1173 * end the name and begin the optional modifier, but not if it
1174 * is immediately followed by the delimiter (%VAR:%). */
1175 SubstStart = Src;
1176 while (*Src != Delim && !(*Src == _T(':') && Src[1] != Delim))
1177 {
1178 if (!*Src)
1179 goto bad_subst;
1180 Src++;
1181 }
1182
1183 EndChr = *Src;
1184 *Src = _T('\0');
1185 Var = GetEnvVarOrSpecial(SubstStart);
1186 *Src++ = EndChr;
1187 if (Var == NULL)
1188 {
1189 /* In a batch file, %NONEXISTENT% "expands" to an empty string */
1190 if (bc)
1191 continue;
1192 goto bad_subst;
1193 }
1194 VarLength = _tcslen(Var);
1195
1196 if (EndChr == Delim)
1197 {
1198 /* %VAR% - use as-is */
1199 APPEND(Var, VarLength)
1200 }
1201 else if (*Src == _T('~'))
1202 {
1203 /* %VAR:~[start][,length]% - substring
1204 * Negative values are offsets from the end */
1205 int Start = _tcstol(Src + 1, &Src, 0);
1206 int End = VarLength;
1207 if (Start < 0)
1208 Start += VarLength;
1209 Start = max(Start, 0);
1210 Start = min(Start, VarLength);
1211 if (*Src == _T(','))
1212 {
1213 End = _tcstol(Src + 1, &Src, 0);
1214 End += (End < 0) ? VarLength : Start;
1215 End = max(End, Start);
1216 End = min(End, VarLength);
1217 }
1218 if (*Src++ != Delim)
1219 goto bad_subst;
1220 APPEND(&Var[Start], End - Start);
1221 }
1222 else
1223 {
1224 /* %VAR:old=new% - replace all occurrences of old with new
1225 * %VAR:*old=new% - replace first occurrence only,
1226 * and remove everything before it */
1227 TCHAR *Old, *New;
1228 DWORD OldLength, NewLength;
1229 BOOL Star = FALSE;
1230 int LastMatch = 0, i = 0;
1231
1232 if (*Src == _T('*'))
1233 {
1234 Star = TRUE;
1235 Src++;
1236 }
1237
1238 /* the string to replace may contain the delimiter */
1239 Src = _tcschr(Old = Src, _T('='));
1240 if (Src == NULL)
1241 goto bad_subst;
1242 OldLength = Src++ - Old;
1243 if (OldLength == 0)
1244 goto bad_subst;
1245
1246 Src = _tcschr(New = Src, Delim);
1247 if (Src == NULL)
1248 goto bad_subst;
1249 NewLength = Src++ - New;
1250
1251 while (i < VarLength)
1252 {
1253 if (_tcsnicmp(&Var[i], Old, OldLength) == 0)
1254 {
1255 if (!Star)
1256 APPEND(&Var[LastMatch], i - LastMatch)
1257 APPEND(New, NewLength)
1258 i += OldLength;
1259 LastMatch = i;
1260 if (Star)
1261 break;
1262 continue;
1263 }
1264 i++;
1265 }
1266 APPEND(&Var[LastMatch], VarLength - LastMatch)
1267 }
1268 continue;
1269
1270 bad_subst:
1271 Src = SubstStart;
1272 if (!bc)
1273 APPEND1(Delim)
1274 }
1275 *Dest = _T('\0');
1276 return TRUE;
1277 too_long:
1278 ConOutResPrintf(STRING_ALIAS_ERROR);
1279 nErrorLevel = 9023;
1280 return FALSE;
1281 #undef APPEND
1282 #undef APPEND1
1283 }
1284
1285 /* Search the list of FOR contexts for a variable */
1286 static LPTSTR FindForVar(TCHAR Var, BOOL *IsParam0)
1287 {
1288 FOR_CONTEXT *Ctx;
1289 *IsParam0 = FALSE;
1290 for (Ctx = fc; Ctx != NULL; Ctx = Ctx->prev)
1291 {
1292 if ((UINT)(Var - Ctx->firstvar) < Ctx->varcount)
1293 return Ctx->values[Var - Ctx->firstvar];
1294 }
1295 return NULL;
1296 }
1297
1298 BOOL
1299 SubstituteForVars(TCHAR *Src, TCHAR *Dest)
1300 {
1301 TCHAR *DestEnd = &Dest[CMDLINE_LENGTH - 1];
1302 while (*Src)
1303 {
1304 if (Src[0] == _T('%'))
1305 {
1306 BOOL Dummy;
1307 LPTSTR End = &Src[2];
1308 LPTSTR Value = NULL;
1309
1310 if (Src[1] == _T('~'))
1311 Value = GetEnhancedVar(&End, FindForVar);
1312
1313 if (!Value)
1314 Value = FindForVar(Src[1], &Dummy);
1315
1316 if (Value)
1317 {
1318 if (Dest + _tcslen(Value) > DestEnd)
1319 return FALSE;
1320 Dest = _stpcpy(Dest, Value);
1321 Src = End;
1322 continue;
1323 }
1324 }
1325 /* Not a variable; just copy the character */
1326 if (Dest >= DestEnd)
1327 return FALSE;
1328 *Dest++ = *Src++;
1329 }
1330 *Dest = _T('\0');
1331 return TRUE;
1332 }
1333
1334 LPTSTR
1335 DoDelayedExpansion(LPTSTR Line)
1336 {
1337 TCHAR Buf1[CMDLINE_LENGTH];
1338 TCHAR Buf2[CMDLINE_LENGTH];
1339
1340 /* First, substitute FOR variables */
1341 if (!SubstituteForVars(Line, Buf1))
1342 return NULL;
1343
1344 if (!bDelayedExpansion || !_tcschr(Buf1, _T('!')))
1345 return cmd_dup(Buf1);
1346
1347 /* FIXME: Delayed substitutions actually aren't quite the same as
1348 * immediate substitutions. In particular, it's possible to escape
1349 * the exclamation point using ^. */
1350 if (!SubstituteVars(Buf1, Buf2, _T('!')))
1351 return NULL;
1352 return cmd_dup(Buf2);
1353 }
1354
1355
1356 /*
1357 * do the prompt/input/process loop
1358 *
1359 */
1360
1361 BOOL
1362 ReadLine(TCHAR *commandline, BOOL bMore)
1363 {
1364 TCHAR readline[CMDLINE_LENGTH];
1365 LPTSTR ip;
1366
1367 /* if no batch input then... */
1368 if (bc == NULL)
1369 {
1370 if (bMore)
1371 {
1372 ConOutResPrintf(STRING_MORE);
1373 }
1374 else
1375 {
1376 /* JPP 19980807 - if echo off, don't print prompt */
1377 if (bEcho)
1378 {
1379 if (!bIgnoreEcho)
1380 ConOutChar(_T('\n'));
1381 PrintPrompt();
1382 }
1383 }
1384
1385 if (!ReadCommand(readline, CMDLINE_LENGTH - 1))
1386 {
1387 bExit = TRUE;
1388 return FALSE;
1389 }
1390
1391 if (CheckCtrlBreak(BREAK_INPUT))
1392 {
1393 ConOutChar(_T('\n'));
1394 return FALSE;
1395 }
1396 ip = readline;
1397 }
1398 else
1399 {
1400 ip = ReadBatchLine();
1401 if (!ip)
1402 return FALSE;
1403 }
1404
1405 return SubstituteVars(ip, commandline, _T('%'));
1406 }
1407
1408 static VOID
1409 ProcessInput()
1410 {
1411 PARSED_COMMAND *Cmd;
1412
1413 while (!bCanExit || !bExit)
1414 {
1415 Cmd = ParseCommand(NULL);
1416 if (!Cmd)
1417 continue;
1418
1419 ExecuteCommand(Cmd);
1420 FreeCommand(Cmd);
1421 }
1422 }
1423
1424
1425 /*
1426 * control-break handler.
1427 */
1428 BOOL WINAPI BreakHandler(DWORD dwCtrlType)
1429 {
1430 DWORD dwWritten;
1431 INPUT_RECORD rec;
1432 static BOOL SelfGenerated = FALSE;
1433
1434 if ((dwCtrlType != CTRL_C_EVENT) &&
1435 (dwCtrlType != CTRL_BREAK_EVENT))
1436 {
1437 return FALSE;
1438 }
1439 else
1440 {
1441 if (SelfGenerated)
1442 {
1443 SelfGenerated = FALSE;
1444 return TRUE;
1445 }
1446 }
1447
1448 if (!TryEnterCriticalSection(&ChildProcessRunningLock))
1449 {
1450 SelfGenerated = TRUE;
1451 GenerateConsoleCtrlEvent (dwCtrlType, 0);
1452 return TRUE;
1453 }
1454 else
1455 {
1456 LeaveCriticalSection(&ChildProcessRunningLock);
1457 }
1458
1459 rec.EventType = KEY_EVENT;
1460 rec.Event.KeyEvent.bKeyDown = TRUE;
1461 rec.Event.KeyEvent.wRepeatCount = 1;
1462 rec.Event.KeyEvent.wVirtualKeyCode = _T('C');
1463 rec.Event.KeyEvent.wVirtualScanCode = _T('C') - 35;
1464 rec.Event.KeyEvent.uChar.AsciiChar = _T('C');
1465 rec.Event.KeyEvent.uChar.UnicodeChar = _T('C');
1466 rec.Event.KeyEvent.dwControlKeyState = RIGHT_CTRL_PRESSED;
1467
1468 WriteConsoleInput(hIn,
1469 &rec,
1470 1,
1471 &dwWritten);
1472
1473 bCtrlBreak = TRUE;
1474 /* FIXME: Handle batch files */
1475
1476 //ConOutPrintf(_T("^C"));
1477
1478 return TRUE;
1479 }
1480
1481
1482 VOID AddBreakHandler (VOID)
1483 {
1484 SetConsoleCtrlHandler ((PHANDLER_ROUTINE)BreakHandler, TRUE);
1485 }
1486
1487
1488 VOID RemoveBreakHandler (VOID)
1489 {
1490 SetConsoleCtrlHandler ((PHANDLER_ROUTINE)BreakHandler, FALSE);
1491 }
1492
1493
1494 /*
1495 * show commands and options that are available.
1496 *
1497 */
1498 #if 0
1499 static VOID
1500 ShowCommands (VOID)
1501 {
1502 /* print command list */
1503 ConOutResPuts(STRING_CMD_HELP1);
1504 PrintCommandList();
1505
1506 /* print feature list */
1507 ConOutResPuts(STRING_CMD_HELP2);
1508
1509 #ifdef FEATURE_ALIASES
1510 ConOutResPuts(STRING_CMD_HELP3);
1511 #endif
1512 #ifdef FEATURE_HISTORY
1513 ConOutResPuts(STRING_CMD_HELP4);
1514 #endif
1515 #ifdef FEATURE_UNIX_FILENAME_COMPLETION
1516 ConOutResPuts(STRING_CMD_HELP5);
1517 #endif
1518 #ifdef FEATURE_DIRECTORY_STACK
1519 ConOutResPuts(STRING_CMD_HELP6);
1520 #endif
1521 #ifdef FEATURE_REDIRECTION
1522 ConOutResPuts(STRING_CMD_HELP7);
1523 #endif
1524 ConOutChar(_T('\n'));
1525 }
1526 #endif
1527
1528 static VOID
1529 ExecuteAutoRunFile(HKEY hkeyRoot)
1530 {
1531 TCHAR autorun[2048];
1532 DWORD len = sizeof autorun;
1533 HKEY hkey;
1534
1535 if (RegOpenKeyEx(hkeyRoot,
1536 _T("SOFTWARE\\Microsoft\\Command Processor"),
1537 0,
1538 KEY_READ,
1539 &hkey) == ERROR_SUCCESS)
1540 {
1541 if (RegQueryValueEx(hkey,
1542 _T("AutoRun"),
1543 0,
1544 0,
1545 (LPBYTE)autorun,
1546 &len) == ERROR_SUCCESS)
1547 {
1548 if (*autorun)
1549 ParseCommandLine(autorun);
1550 }
1551 RegCloseKey(hkey);
1552 }
1553 }
1554
1555 /* Get the command that comes after a /C or /K switch */
1556 static VOID
1557 GetCmdLineCommand(TCHAR *commandline, TCHAR *ptr, BOOL AlwaysStrip)
1558 {
1559 TCHAR *LastQuote;
1560
1561 while (_istspace(*ptr))
1562 ptr++;
1563
1564 /* Remove leading quote, find final quote */
1565 if (*ptr == _T('"') &&
1566 (LastQuote = _tcsrchr(++ptr, _T('"'))) != NULL)
1567 {
1568 TCHAR *Space;
1569 /* Under certain circumstances, all quotes are preserved.
1570 * CMD /? documents these conditions as follows:
1571 * 1. No /S switch
1572 * 2. Exactly two quotes
1573 * 3. No "special characters" between the quotes
1574 * (CMD /? says &<>()@^| but parentheses did not
1575 * trigger this rule when I tested them.)
1576 * 4. Whitespace exists between the quotes
1577 * 5. Enclosed string is an executable filename
1578 */
1579 *LastQuote = _T('\0');
1580 for (Space = ptr + 1; Space < LastQuote; Space++)
1581 {
1582 if (_istspace(*Space)) /* Rule 4 */
1583 {
1584 if (!AlwaysStrip && /* Rule 1 */
1585 !_tcspbrk(ptr, _T("\"&<>@^|")) && /* Rules 2, 3 */
1586 SearchForExecutable(ptr, commandline)) /* Rule 5 */
1587 {
1588 /* All conditions met: preserve both the quotes */
1589 *LastQuote = _T('"');
1590 _tcscpy(commandline, ptr - 1);
1591 return;
1592 }
1593 break;
1594 }
1595 }
1596
1597 /* The conditions were not met: remove both the
1598 * leading quote and the last quote */
1599 _tcscpy(commandline, ptr);
1600 _tcscpy(&commandline[LastQuote - ptr], LastQuote + 1);
1601 return;
1602 }
1603
1604 /* No quotes; just copy */
1605 _tcscpy(commandline, ptr);
1606 }
1607
1608 /*
1609 * set up global initializations and process parameters
1610 */
1611 static VOID
1612 Initialize()
1613 {
1614 HMODULE NtDllModule;
1615 TCHAR commandline[CMDLINE_LENGTH];
1616 TCHAR ModuleName[_MAX_PATH + 1];
1617 INT nExitCode;
1618
1619 //INT len;
1620 TCHAR *ptr, *cmdLine, option = 0;
1621 BOOL AlwaysStrip = FALSE;
1622 BOOL AutoRun = TRUE;
1623
1624 /* Get version information */
1625 InitOSVersion();
1626
1627 /* Some people like to run ReactOS cmd.exe on Win98, it helps in the
1628 * build process. So don't link implicitly against ntdll.dll, load it
1629 * dynamically instead */
1630 NtDllModule = GetModuleHandle(TEXT("ntdll.dll"));
1631 if (NtDllModule != NULL)
1632 {
1633 NtQueryInformationProcessPtr = (NtQueryInformationProcessProc)GetProcAddress(NtDllModule, "NtQueryInformationProcess");
1634 NtReadVirtualMemoryPtr = (NtReadVirtualMemoryProc)GetProcAddress(NtDllModule, "NtReadVirtualMemory");
1635 }
1636
1637 InitLocale();
1638
1639 /* get default input and output console handles */
1640 hOut = GetStdHandle(STD_OUTPUT_HANDLE);
1641 hIn = GetStdHandle(STD_INPUT_HANDLE);
1642
1643 /* Initialize prompt support */
1644 InitPrompt();
1645
1646 #ifdef FEATURE_DIR_STACK
1647 /* initialize directory stack */
1648 InitDirectoryStack();
1649 #endif
1650
1651 #ifdef FEATURE_HISTORY
1652 /*initialize history*/
1653 InitHistory();
1654 #endif
1655
1656 /* Set COMSPEC environment variable */
1657 if (0 != GetModuleFileName (NULL, ModuleName, _MAX_PATH + 1))
1658 {
1659 ModuleName[_MAX_PATH] = _T('\0');
1660 SetEnvironmentVariable (_T("COMSPEC"), ModuleName);
1661 }
1662
1663 /* Add ctrl break handler */
1664 AddBreakHandler();
1665
1666 /* Set our default console mode */
1667 SetConsoleMode(hOut, 0); // Reinitialize the console output mode
1668 SetConsoleMode(hOut, ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
1669 SetConsoleMode(hIn , ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT);
1670
1671 cmdLine = GetCommandLine();
1672 TRACE ("[command args: %s]\n", debugstr_aw(cmdLine));
1673
1674 for (ptr = cmdLine; *ptr; ptr++)
1675 {
1676 if (*ptr == _T('/'))
1677 {
1678 option = _totupper(ptr[1]);
1679 if (option == _T('?'))
1680 {
1681 ConOutResPaging(TRUE,STRING_CMD_HELP8);
1682 nErrorLevel = 1;
1683 bExit = TRUE;
1684 return;
1685 }
1686 else if (option == _T('P'))
1687 {
1688 if (!IsExistingFile (_T("\\autoexec.bat")))
1689 {
1690 #ifdef INCLUDE_CMD_DATE
1691 cmd_date (_T(""));
1692 #endif
1693 #ifdef INCLUDE_CMD_TIME
1694 cmd_time (_T(""));
1695 #endif
1696 }
1697 else
1698 {
1699 ParseCommandLine (_T("\\autoexec.bat"));
1700 }
1701 bCanExit = FALSE;
1702 }
1703 else if (option == _T('A'))
1704 {
1705 bUnicodeOutput = FALSE;
1706 }
1707 else if (option == _T('C') || option == _T('K') || option == _T('R'))
1708 {
1709 /* Remainder of command line is a command to be run */
1710 break;
1711 }
1712 else if (option == _T('D'))
1713 {
1714 AutoRun = FALSE;
1715 }
1716 else if (option == _T('Q'))
1717 {
1718 bDisableBatchEcho = TRUE;
1719 }
1720 else if (option == _T('S'))
1721 {
1722 AlwaysStrip = TRUE;
1723 }
1724 #ifdef INCLUDE_CMD_COLOR
1725 else if (!_tcsnicmp(ptr, _T("/T:"), 3))
1726 {
1727 /* process /T (color) argument */
1728 wDefColor = (WORD)_tcstoul(&ptr[3], &ptr, 16);
1729 SetScreenColor(wDefColor, FALSE);
1730 }
1731 #endif
1732 else if (option == _T('U'))
1733 {
1734 bUnicodeOutput = TRUE;
1735 }
1736 else if (option == _T('V'))
1737 {
1738 bDelayedExpansion = _tcsnicmp(&ptr[2], _T(":OFF"), 4);
1739 }
1740 }
1741 }
1742
1743 if (!*ptr)
1744 {
1745 /* If neither /C or /K was given, display a simple version string */
1746 ConOutChar(_T('\n'));
1747 ConOutResPrintf(STRING_REACTOS_VERSION,
1748 _T(KERNEL_RELEASE_STR),
1749 _T(KERNEL_VERSION_BUILD_STR));
1750 ConOutPuts(_T("(C) Copyright 1998-") _T(COPYRIGHT_YEAR) _T(" ReactOS Team.\n"));
1751 }
1752
1753 if (AutoRun)
1754 {
1755 ExecuteAutoRunFile(HKEY_LOCAL_MACHINE);
1756 ExecuteAutoRunFile(HKEY_CURRENT_USER);
1757 }
1758
1759 if (*ptr)
1760 {
1761 /* Do the /C or /K command */
1762 GetCmdLineCommand(commandline, &ptr[2], AlwaysStrip);
1763 nExitCode = ParseCommandLine(commandline);
1764 if (option != _T('K'))
1765 {
1766 nErrorLevel = nExitCode;
1767 bExit = TRUE;
1768 }
1769 }
1770 }
1771
1772
1773 static VOID Cleanup()
1774 {
1775 /* run cmdexit.bat */
1776 if (IsExistingFile (_T("cmdexit.bat")))
1777 {
1778 ConErrResPuts(STRING_CMD_ERROR5);
1779
1780 ParseCommandLine (_T("cmdexit.bat"));
1781 }
1782 else if (IsExistingFile (_T("\\cmdexit.bat")))
1783 {
1784 ConErrResPuts (STRING_CMD_ERROR5);
1785 ParseCommandLine (_T("\\cmdexit.bat"));
1786 }
1787
1788 #ifdef FEATURE_DIECTORY_STACK
1789 /* destroy directory stack */
1790 DestroyDirectoryStack ();
1791 #endif
1792
1793 #ifdef FEATURE_HISTORY
1794 CleanHistory();
1795 #endif
1796
1797 /* free GetEnvVar's buffer */
1798 GetEnvVar(NULL);
1799
1800 /* Remove ctrl break handler */
1801 RemoveBreakHandler();
1802
1803 /* Restore the default console mode */
1804 SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE),
1805 ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT);
1806 SetConsoleMode(GetStdHandle(STD_OUTPUT_HANDLE),
1807 ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
1808
1809 DeleteCriticalSection(&ChildProcessRunningLock);
1810 }
1811
1812 /*
1813 * main function
1814 */
1815 int _tmain(int argc, const TCHAR *argv[])
1816 {
1817 HANDLE hConsole;
1818 TCHAR startPath[MAX_PATH];
1819 CONSOLE_SCREEN_BUFFER_INFO Info;
1820
1821 InitializeCriticalSection(&ChildProcessRunningLock);
1822 lpOriginalEnvironment = DuplicateEnvironment();
1823
1824 GetCurrentDirectory(MAX_PATH,startPath);
1825 _tchdir(startPath);
1826
1827 SetFileApisToOEM();
1828 InputCodePage = 0;
1829 OutputCodePage = 0;
1830
1831 hConsole = CreateFile(_T("CONOUT$"), GENERIC_READ|GENERIC_WRITE,
1832 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL,
1833 OPEN_EXISTING, 0, NULL);
1834 if (hConsole != INVALID_HANDLE_VALUE)
1835 {
1836 if (!GetConsoleScreenBufferInfo(hConsole, &Info))
1837 {
1838 ConErrFormatMessage(GetLastError());
1839 CloseHandle(hConsole);
1840 return(1);
1841 }
1842 wDefColor = Info.wAttributes;
1843 CloseHandle(hConsole);
1844 }
1845
1846 InputCodePage = GetConsoleCP();
1847 OutputCodePage = GetConsoleOutputCP();
1848 CMD_ModuleHandle = GetModuleHandle(NULL);
1849
1850 /* check switches on command-line */
1851 Initialize();
1852
1853 /* call prompt routine */
1854 ProcessInput();
1855
1856 /* do the cleanup */
1857 Cleanup();
1858
1859 cmd_free(lpOriginalEnvironment);
1860
1861 cmd_exit(nErrorLevel);
1862 return(nErrorLevel);
1863 }
1864
1865 /* EOF */