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