sync to trunk revision 36500
[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 BOOL bChildProcessRunning = FALSE;
160 DWORD dwChildProcessId = 0;
161 OSVERSIONINFO osvi;
162 HANDLE hIn;
163 HANDLE hOut;
164 HANDLE hConsole;
165 HANDLE CMD_ModuleHandle;
166 HMODULE NtDllModule;
167
168 static NtQueryInformationProcessProc NtQueryInformationProcessPtr = NULL;
169 static NtReadVirtualMemoryProc NtReadVirtualMemoryPtr = NULL;
170
171 #ifdef INCLUDE_CMD_COLOR
172 WORD wColor; /* current color */
173 WORD wDefColor; /* default color */
174 #endif
175
176 /*
177 * convert
178 *
179 * insert commas into a number
180 */
181 INT
182 ConvertULargeInteger (ULARGE_INTEGER num, LPTSTR des, INT len, BOOL bPutSeperator)
183 {
184 TCHAR temp[32];
185 UINT n, iTarget;
186
187 if (len <= 1)
188 return 0;
189
190 if (num.QuadPart == 0)
191 {
192 des[0] = _T('0');
193 des[1] = _T('\0');
194 return 1;
195 }
196
197 n = 0;
198 iTarget = nNumberGroups;
199 if (!nNumberGroups)
200 bPutSeperator = FALSE;
201
202 while (num.QuadPart > 0)
203 {
204 if (iTarget == n && bPutSeperator)
205 {
206 iTarget += nNumberGroups + 1;
207 temp[31 - n++] = cThousandSeparator;
208 }
209 temp[31 - n++] = (TCHAR)(num.QuadPart % 10) + _T('0');
210 num.QuadPart /= 10;
211 }
212 if (n > len-1)
213 n = len-1;
214
215 memcpy(des, temp + 32 - n, n * sizeof(TCHAR));
216 des[n] = _T('\0');
217
218 return n;
219 }
220
221 /*
222 * is character a delimeter when used on first word?
223 *
224 */
225 static BOOL IsDelimiter (TCHAR c)
226 {
227 return (c == _T('/') || c == _T('=') || c == _T('\0') || _istspace (c));
228 }
229
230 /*
231 * Is a process a console process?
232 */
233 static BOOL IsConsoleProcess(HANDLE Process)
234 {
235 NTSTATUS Status;
236 PROCESS_BASIC_INFORMATION Info;
237 PEB ProcessPeb;
238 ULONG BytesRead;
239
240 if (NULL == NtQueryInformationProcessPtr || NULL == NtReadVirtualMemoryPtr)
241 {
242 return TRUE;
243 }
244
245 Status = NtQueryInformationProcessPtr (
246 Process, ProcessBasicInformation,
247 &Info, sizeof(PROCESS_BASIC_INFORMATION), NULL);
248 if (! NT_SUCCESS(Status))
249 {
250 WARN ("NtQueryInformationProcess failed with status %08x\n", Status);
251 return TRUE;
252 }
253 Status = NtReadVirtualMemoryPtr (
254 Process, Info.PebBaseAddress, &ProcessPeb,
255 sizeof(PEB), &BytesRead);
256 if (! NT_SUCCESS(Status) || sizeof(PEB) != BytesRead)
257 {
258 WARN ("Couldn't read virt mem status %08x bytes read %lu\n", Status, BytesRead);
259 return TRUE;
260 }
261
262 return IMAGE_SUBSYSTEM_WINDOWS_CUI == ProcessPeb.ImageSubSystem;
263 }
264
265
266
267 #ifdef _UNICODE
268 #define SHELLEXECUTETEXT "ShellExecuteW"
269 #else
270 #define SHELLEXECUTETEXT "ShellExecuteA"
271 #endif
272
273 typedef HINSTANCE (WINAPI *MYEX)(
274 HWND hwnd,
275 LPCTSTR lpOperation,
276 LPCTSTR lpFile,
277 LPCTSTR lpParameters,
278 LPCTSTR lpDirectory,
279 INT nShowCmd
280 );
281
282
283
284 static BOOL RunFile(LPTSTR filename)
285 {
286 HMODULE hShell32;
287 MYEX hShExt;
288 HINSTANCE ret;
289
290 TRACE ("RunFile(%s)\n", debugstr_aw(filename));
291 hShell32 = LoadLibrary(_T("SHELL32.DLL"));
292 if (!hShell32)
293 {
294 WARN ("RunFile: couldn't load SHELL32.DLL!\n");
295 return FALSE;
296 }
297
298 hShExt = (MYEX)(FARPROC)GetProcAddress(hShell32, SHELLEXECUTETEXT);
299 if (!hShExt)
300 {
301 WARN ("RunFile: couldn't find ShellExecuteA/W in SHELL32.DLL!\n");
302 FreeLibrary(hShell32);
303 return FALSE;
304 }
305
306 TRACE ("RunFile: ShellExecuteA/W is at %x\n", hShExt);
307
308 ret = (hShExt)(NULL, _T("open"), filename, NULL, NULL, SW_SHOWNORMAL);
309
310 TRACE ("RunFile: ShellExecuteA/W returned %p\n", (DWORD_PTR)ret);
311
312 FreeLibrary(hShell32);
313 return (((DWORD_PTR)ret) > 32);
314 }
315
316
317
318 /*
319 * This command (in first) was not found in the command table
320 *
321 * Full - whole command line
322 * First - first word on command line
323 * Rest - rest of command line
324 */
325
326 static BOOL
327 Execute (LPTSTR Full, LPTSTR First, LPTSTR Rest)
328 {
329 TCHAR *szFullName=NULL;
330 TCHAR *first = NULL;
331 TCHAR *rest = NULL;
332 TCHAR *full = NULL;
333 TCHAR *dot = NULL;
334 TCHAR szWindowTitle[MAX_PATH];
335 DWORD dwExitCode = 0;
336
337 TRACE ("Execute: \'%s\' \'%s\'\n", debugstr_aw(first), debugstr_aw(rest));
338
339 /* we need biger buffer that First, Rest, Full are already
340 need rewrite some code to use cmd_realloc when it need instead
341 of add 512bytes extra */
342
343 first = cmd_alloc ( (_tcslen(First) + 512) * sizeof(TCHAR));
344 if (first == NULL)
345 {
346 error_out_of_memory();
347 nErrorLevel = 1;
348 return FALSE;
349 }
350
351 rest = cmd_alloc ( (_tcslen(Rest) + 512) * sizeof(TCHAR));
352 if (rest == NULL)
353 {
354 cmd_free (first);
355 error_out_of_memory();
356 nErrorLevel = 1;
357 return FALSE;
358 }
359
360 full = cmd_alloc ( (_tcslen(Full) + 512) * sizeof(TCHAR));
361 if (full == NULL)
362 {
363 cmd_free (first);
364 cmd_free (rest);
365 error_out_of_memory();
366 nErrorLevel = 1;
367 return FALSE;
368 }
369
370 szFullName = cmd_alloc ( (_tcslen(Full) + 512) * sizeof(TCHAR));
371 if (full == NULL)
372 {
373 cmd_free (first);
374 cmd_free (rest);
375 cmd_free (full);
376 error_out_of_memory();
377 nErrorLevel = 1;
378 return FALSE;
379 }
380
381
382 /* Though it was already parsed once, we have a different set of rules
383 for parsing before we pass to CreateProccess */
384 if(!_tcschr(Full,_T('\"')))
385 {
386 _tcscpy(first,First);
387 _tcscpy(rest,Rest);
388 _tcscpy(full,Full);
389 }
390 else
391 {
392 UINT i = 0;
393 BOOL bInside = FALSE;
394 rest[0] = _T('\0');
395 full[0] = _T('\0');
396 first[0] = _T('\0');
397 _tcscpy(first,Full);
398 /* find the end of the command and start of the args */
399 for(i = 0; i < _tcslen(first); i++)
400 {
401 if(!_tcsncmp(&first[i], _T("\""), 1))
402 bInside = !bInside;
403 if(!_tcsncmp(&first[i], _T(" "), 1) && !bInside)
404 {
405 _tcscpy(rest,&first[i]);
406 first[i] = _T('\0');
407 break;
408 }
409
410 }
411 i = 0;
412 /* remove any slashes */
413 while(i < _tcslen(first))
414 {
415 if(first[i] == _T('\"'))
416 memmove(&first[i],&first[i + 1], _tcslen(&first[i]) * sizeof(TCHAR));
417 else
418 i++;
419 }
420 /* Drop quotes around it just in case there is a space */
421 _tcscpy(full,_T("\""));
422 _tcscat(full,first);
423 _tcscat(full,_T("\" "));
424 _tcscat(full,rest);
425 }
426
427 /* check for a drive change */
428 if ((_istalpha (first[0])) && (!_tcscmp (first + 1, _T(":"))))
429 {
430 BOOL working = TRUE;
431 if (!SetCurrentDirectory(first))
432 /* Guess they changed disc or something, handle that gracefully and get to root */
433 {
434 TCHAR str[4];
435 str[0]=first[0];
436 str[1]=_T(':');
437 str[2]=_T('\\');
438 str[3]=0;
439 working = SetCurrentDirectory(str);
440 }
441
442 if (!working) ConErrResPuts (STRING_FREE_ERROR1);
443
444 cmd_free (first);
445 cmd_free (rest);
446 cmd_free (full);
447 cmd_free (szFullName);
448 nErrorLevel = 1;
449 return working;
450 }
451
452 /* get the PATH environment variable and parse it */
453 /* search the PATH environment variable for the binary */
454 if (!SearchForExecutable (first, szFullName))
455 {
456 error_bad_command ();
457 cmd_free (first);
458 cmd_free (rest);
459 cmd_free (full);
460 cmd_free (szFullName);
461 nErrorLevel = 1;
462 return FALSE;
463
464 }
465
466 GetConsoleTitle (szWindowTitle, MAX_PATH);
467
468 /* check if this is a .BAT or .CMD file */
469 dot = _tcsrchr (szFullName, _T('.'));
470 if (dot && (!_tcsicmp (dot, _T(".bat")) || !_tcsicmp (dot, _T(".cmd"))))
471 {
472 TRACE ("[BATCH: %s %s]\n", debugstr_aw(szFullName), debugstr_aw(rest));
473 Batch (szFullName, first, rest, FALSE);
474 }
475 else
476 {
477 /* exec the program */
478 PROCESS_INFORMATION prci;
479 STARTUPINFO stui;
480
481 TRACE ("[EXEC: %s %s]\n", debugstr_aw(full), debugstr_aw(rest));
482 /* build command line for CreateProcess() */
483
484 /* fill startup info */
485 memset (&stui, 0, sizeof (STARTUPINFO));
486 stui.cb = sizeof (STARTUPINFO);
487 stui.dwFlags = STARTF_USESHOWWINDOW;
488 stui.wShowWindow = SW_SHOWDEFAULT;
489
490 // return console to standard mode
491 SetConsoleMode (GetStdHandle(STD_INPUT_HANDLE),
492 ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT | ENABLE_ECHO_INPUT );
493
494 if (CreateProcess (szFullName,
495 full,
496 NULL,
497 NULL,
498 TRUE,
499 0, /* CREATE_NEW_PROCESS_GROUP */
500 NULL,
501 NULL,
502 &stui,
503 &prci))
504
505 {
506 if (IsConsoleProcess(prci.hProcess))
507 {
508 /* FIXME: Protect this with critical section */
509 bChildProcessRunning = TRUE;
510 dwChildProcessId = prci.dwProcessId;
511
512 WaitForSingleObject (prci.hProcess, INFINITE);
513
514 /* FIXME: Protect this with critical section */
515 bChildProcessRunning = FALSE;
516
517 GetExitCodeProcess (prci.hProcess, &dwExitCode);
518 nErrorLevel = (INT)dwExitCode;
519 }
520 else
521 {
522 nErrorLevel = 0;
523 }
524 CloseHandle (prci.hThread);
525 CloseHandle (prci.hProcess);
526 }
527 else
528 {
529 TRACE ("[ShellExecute: %s]\n", debugstr_aw(full));
530 // See if we can run this with ShellExecute() ie myfile.xls
531 if (!RunFile(full))
532 {
533 TRACE ("[ShellExecute failed!: %s]\n", debugstr_aw(full));
534 error_bad_command ();
535 nErrorLevel = 1;
536 }
537 else
538 {
539 nErrorLevel = 0;
540 }
541 }
542 // restore console mode
543 SetConsoleMode (
544 GetStdHandle( STD_INPUT_HANDLE ),
545 ENABLE_PROCESSED_INPUT );
546 }
547
548 /* Get code page if it has been change */
549 InputCodePage= GetConsoleCP();
550 OutputCodePage = GetConsoleOutputCP();
551 SetConsoleTitle (szWindowTitle);
552
553 cmd_free(first);
554 cmd_free(rest);
555 cmd_free(full);
556 cmd_free (szFullName);
557 return nErrorLevel == 0;
558 }
559
560
561 /*
562 * look through the internal commands and determine whether or not this
563 * command is one of them. If it is, call the command. If not, call
564 * execute to run it as an external program.
565 *
566 * line - the command line of the program to run
567 *
568 */
569
570 BOOL
571 DoCommand (LPTSTR line)
572 {
573 TCHAR *com = NULL; /* the first word in the command */
574 TCHAR *cp = NULL;
575 LPTSTR cstart;
576 LPTSTR rest; /* pointer to the rest of the command line */
577 INT cl;
578 LPCOMMAND cmdptr;
579 BOOL ret = TRUE;
580
581 TRACE ("DoCommand: (\'%s\')\n", debugstr_aw(line));
582
583 com = cmd_alloc( (_tcslen(line) +512)*sizeof(TCHAR) );
584 if (com == NULL)
585 {
586 error_out_of_memory();
587 return FALSE;
588 }
589
590 cp = com;
591 /* Skip over initial white space */
592 while (_istspace (*line))
593 line++;
594 rest = line;
595
596 cstart = rest;
597
598 /* Anything to do ? */
599 if (*rest)
600 {
601 if (*rest == _T('"'))
602 {
603 /* treat quoted words specially */
604
605 rest++;
606
607 while(*rest != _T('\0') && *rest != _T('"'))
608 *cp++ = _totlower (*rest++);
609 if (*rest == _T('"'))
610 rest++;
611 }
612 else
613 {
614 while (!IsDelimiter (*rest))
615 *cp++ = _totlower (*rest++);
616 }
617
618
619 /* Terminate first word */
620 *cp = _T('\0');
621
622 /* Do not limit commands to MAX_PATH */
623 /*
624 if(_tcslen(com) > MAX_PATH)
625 {
626 error_bad_command();
627 cmd_free(com);
628 return;
629 }
630 */
631
632 /* Skip over whitespace to rest of line, exclude 'echo' command */
633 if (_tcsicmp (com, _T("echo")))
634 {
635 while (_istspace (*rest))
636 rest++;
637 }
638
639 /* Scan internal command table */
640 for (cmdptr = cmds;; cmdptr++)
641 {
642 /* If end of table execute ext cmd */
643 if (cmdptr->name == NULL)
644 {
645 ret = Execute (line, com, rest);
646 break;
647 }
648
649 if (!_tcscmp (com, cmdptr->name))
650 {
651 cmdptr->func (rest);
652 break;
653 }
654
655 /* The following code handles the case of commands like CD which
656 * are recognised even when the command name and parameter are
657 * not space separated.
658 *
659 * e.g dir..
660 * cd\freda
661 */
662
663 /* Get length of command name */
664 cl = _tcslen (cmdptr->name);
665
666 if ((cmdptr->flags & CMD_SPECIAL) &&
667 (!_tcsncmp (cmdptr->name, com, cl)) &&
668 (_tcschr (_T("\\.-"), *(com + cl))))
669 {
670 /* OK its one of the specials...*/
671
672 /* Call with new rest */
673 cmdptr->func (cstart + cl);
674 break;
675 }
676 }
677 }
678 cmd_free(com);
679 return ret;
680 }
681
682
683 /*
684 * process the command line and execute the appropriate functions
685 * full input/output redirection and piping are supported
686 */
687
688 VOID ParseCommandLine (LPTSTR cmd)
689 {
690 PARSED_COMMAND *Cmd = ParseCommand(cmd);
691 if (Cmd)
692 {
693 ExecuteCommand(Cmd);
694 FreeCommand(Cmd);
695 }
696 }
697
698 static VOID
699 ExecutePipeline(PARSED_COMMAND *Cmd)
700 {
701 #ifdef FEATURE_REDIRECTION
702 TCHAR szTempPath[MAX_PATH] = _T(".\\");
703 TCHAR szFileName[2][MAX_PATH] = {_T(""), _T("")};
704 HANDLE hFile[2] = {INVALID_HANDLE_VALUE, INVALID_HANDLE_VALUE};
705 INT Length;
706 UINT Attributes;
707 HANDLE hOldConIn;
708 HANDLE hOldConOut;
709 #endif /* FEATURE_REDIRECTION */
710
711 //TRACE ("ParseCommandLine: (\'%s\')\n", debugstr_aw(s));
712
713 #ifdef FEATURE_REDIRECTION
714 /* find the temp path to store temporary files */
715 Length = GetTempPath (MAX_PATH, szTempPath);
716 if (Length > 0 && Length < MAX_PATH)
717 {
718 Attributes = GetFileAttributes(szTempPath);
719 if (Attributes == 0xffffffff ||
720 !(Attributes & FILE_ATTRIBUTE_DIRECTORY))
721 {
722 Length = 0;
723 }
724 }
725 if (Length == 0 || Length >= MAX_PATH)
726 {
727 _tcscpy(szTempPath, _T(".\\"));
728 }
729 if (szTempPath[_tcslen (szTempPath) - 1] != _T('\\'))
730 _tcscat (szTempPath, _T("\\"));
731
732 /* Set up the initial conditions ... */
733 /* preserve STDIN and STDOUT handles */
734 hOldConIn = GetStdHandle (STD_INPUT_HANDLE);
735 hOldConOut = GetStdHandle (STD_OUTPUT_HANDLE);
736
737 /* Now do all but the last pipe command */
738 *szFileName[0] = _T('\0');
739 hFile[0] = INVALID_HANDLE_VALUE;
740
741 while (Cmd->Type == C_PIPE)
742 {
743 SECURITY_ATTRIBUTES sa = {sizeof(SECURITY_ATTRIBUTES), NULL, TRUE};
744
745 /* Create unique temporary file name */
746 GetTempFileName (szTempPath, _T("CMD"), 0, szFileName[1]);
747
748 /* we need make sure the LastError msg is zero before calling CreateFile */
749 SetLastError(0);
750
751 /* Set current stdout to temporary file */
752 hFile[1] = CreateFile (szFileName[1], GENERIC_WRITE, 0, &sa,
753 TRUNCATE_EXISTING, FILE_ATTRIBUTE_TEMPORARY, NULL);
754
755 if (hFile[1] == INVALID_HANDLE_VALUE)
756 {
757 ConErrResPrintf(STRING_CMD_ERROR2);
758 return;
759 }
760
761 SetStdHandle (STD_OUTPUT_HANDLE, hFile[1]);
762
763 ExecuteCommand(Cmd->Subcommands);
764
765 /* close stdout file */
766 SetStdHandle (STD_OUTPUT_HANDLE, hOldConOut);
767 if ((hFile[1] != INVALID_HANDLE_VALUE) && (hFile[1] != hOldConOut))
768 {
769 CloseHandle (hFile[1]);
770 hFile[1] = INVALID_HANDLE_VALUE;
771 }
772
773 /* close old stdin file */
774 SetStdHandle (STD_INPUT_HANDLE, hOldConIn);
775 if ((hFile[0] != INVALID_HANDLE_VALUE) && (hFile[0] != hOldConIn))
776 {
777 /* delete old stdin file, if it is a real file */
778 CloseHandle (hFile[0]);
779 hFile[0] = INVALID_HANDLE_VALUE;
780 DeleteFile (szFileName[0]);
781 *szFileName[0] = _T('\0');
782 }
783
784 /* copy stdout file name to stdin file name */
785 _tcscpy (szFileName[0], szFileName[1]);
786 *szFileName[1] = _T('\0');
787
788 /* we need make sure the LastError msg is zero before calling CreateFile */
789 SetLastError(0);
790
791 /* open new stdin file */
792 hFile[0] = CreateFile (szFileName[0], GENERIC_READ, 0, &sa,
793 OPEN_EXISTING, FILE_ATTRIBUTE_TEMPORARY, NULL);
794 SetStdHandle (STD_INPUT_HANDLE, hFile[0]);
795
796 Cmd = Cmd->Subcommands->Next;
797 }
798
799 /* Now set up the end conditions... */
800 SetStdHandle(STD_OUTPUT_HANDLE, hOldConOut);
801
802 #endif
803
804 /* process final command */
805 ExecuteCommand(Cmd);
806
807 #ifdef FEATURE_REDIRECTION
808 /* close old stdin file */
809 #if 0 /* buggy implementation */
810 SetStdHandle (STD_INPUT_HANDLE, hOldConIn);
811 if ((hFile[0] != INVALID_HANDLE_VALUE) &&
812 (hFile[0] != hOldConIn))
813 {
814 /* delete old stdin file, if it is a real file */
815 CloseHandle (hFile[0]);
816 hFile[0] = INVALID_HANDLE_VALUE;
817 DeleteFile (szFileName[0]);
818 *szFileName[0] = _T('\0');
819 }
820
821 /* Restore original STDIN */
822 if (hOldConIn != INVALID_HANDLE_VALUE)
823 {
824 HANDLE hIn = GetStdHandle (STD_INPUT_HANDLE);
825 SetStdHandle (STD_INPUT_HANDLE, hOldConIn);
826 if (hOldConIn != hIn)
827 CloseHandle (hIn);
828 hOldConIn = INVALID_HANDLE_VALUE;
829 }
830 else
831 {
832 WARN ("Can't restore STDIN! Is invalid!!\n", out);
833 }
834 #endif /* buggy implementation */
835
836
837 if (hOldConIn != INVALID_HANDLE_VALUE)
838 {
839 HANDLE hIn = GetStdHandle (STD_INPUT_HANDLE);
840 SetStdHandle (STD_INPUT_HANDLE, hOldConIn);
841 if (hIn == INVALID_HANDLE_VALUE)
842 {
843 WARN ("Previous STDIN is invalid!!\n");
844 }
845 else
846 {
847 if (GetFileType (hIn) == FILE_TYPE_DISK)
848 {
849 if (hFile[0] == hIn)
850 {
851 CloseHandle (hFile[0]);
852 hFile[0] = INVALID_HANDLE_VALUE;
853 DeleteFile (szFileName[0]);
854 *szFileName[0] = _T('\0');
855 }
856 else
857 {
858 WARN ("hFile[0] and hIn dont match!!!\n");
859 }
860 }
861 }
862 }
863 #endif /* FEATURE_REDIRECTION */
864 }
865
866 BOOL
867 ExecuteCommand(PARSED_COMMAND *Cmd)
868 {
869 BOOL bNewBatch = TRUE;
870 PARSED_COMMAND *Sub;
871 BOOL Success = TRUE;
872
873 if (!PerformRedirection(Cmd->Redirections))
874 return FALSE;
875
876 switch (Cmd->Type)
877 {
878 case C_COMMAND:
879 if(bc)
880 bNewBatch = FALSE;
881
882 Success = DoCommand(Cmd->CommandLine);
883
884 if(bNewBatch && bc)
885 AddBatchRedirection(&Cmd->Redirections);
886 break;
887 case C_QUIET:
888 case C_BLOCK:
889 case C_MULTI:
890 for (Sub = Cmd->Subcommands; Sub; Sub = Sub->Next)
891 Success = ExecuteCommand(Sub);
892 break;
893 case C_IFFAILURE:
894 case C_IFSUCCESS:
895 Sub = Cmd->Subcommands;
896 Success = ExecuteCommand(Sub);
897 if (Success == (Cmd->Type - C_IFFAILURE))
898 {
899 Sub = Sub->Next;
900 Success = ExecuteCommand(Sub);
901 }
902 break;
903 case C_PIPE:
904 ExecutePipeline(Cmd);
905 break;
906 }
907
908 UndoRedirection(Cmd->Redirections, NULL);
909 return Success;
910 }
911
912 BOOL
913 GrowIfNecessary_dbg ( UINT needed, LPTSTR* ret, UINT* retlen, const char *file, int line )
914 {
915 if ( *ret && needed < *retlen )
916 return TRUE;
917 *retlen = needed;
918 if ( *ret )
919 cmd_free ( *ret );
920 #ifdef _DEBUG_MEM
921 *ret = (LPTSTR)cmd_alloc_dbg ( *retlen * sizeof(TCHAR), file, line );
922 #else
923 *ret = (LPTSTR)cmd_alloc ( *retlen * sizeof(TCHAR) );
924 #endif
925 if ( !*ret )
926 SetLastError ( ERROR_OUTOFMEMORY );
927 return *ret != NULL;
928 }
929 #define GrowIfNecessary(x, y, z) GrowIfNecessary_dbg(x, y, z, __FILE__, __LINE__)
930
931 LPCTSTR
932 GetEnvVarOrSpecial ( LPCTSTR varName )
933 {
934 static LPTSTR ret = NULL;
935 static UINT retlen = 0;
936 UINT size;
937
938 size = GetEnvironmentVariable ( varName, ret, retlen );
939 if ( size > retlen )
940 {
941 if ( !GrowIfNecessary ( size, &ret, &retlen ) )
942 return NULL;
943 size = GetEnvironmentVariable ( varName, ret, retlen );
944 }
945 if ( size )
946 return ret;
947
948 /* env var doesn't exist, look for a "special" one */
949 /* %CD% */
950 if (_tcsicmp(varName,_T("cd")) ==0)
951 {
952 size = GetCurrentDirectory ( retlen, ret );
953 if ( size > retlen )
954 {
955 if ( !GrowIfNecessary ( size, &ret, &retlen ) )
956 return NULL;
957 size = GetCurrentDirectory ( retlen, ret );
958 }
959 if ( !size )
960 return NULL;
961 return ret;
962 }
963 /* %TIME% */
964 else if (_tcsicmp(varName,_T("time")) ==0)
965 {
966 SYSTEMTIME t;
967 if ( !GrowIfNecessary ( MAX_PATH, &ret, &retlen ) )
968 return NULL;
969 GetSystemTime(&t);
970 _sntprintf ( ret, retlen, _T("%02d%c%02d%c%02d%c%02d"),
971 t.wHour, cTimeSeparator, t.wMinute, cTimeSeparator,
972 t.wSecond, cDecimalSeparator, t.wMilliseconds / 10);
973 return ret;
974 }
975 /* %DATE% */
976 else if (_tcsicmp(varName,_T("date")) ==0)
977 {
978
979 if ( !GrowIfNecessary ( GetDateFormat(LOCALE_USER_DEFAULT, DATE_SHORTDATE, NULL, NULL, NULL, 0), &ret, &retlen ) )
980 return NULL;
981
982 size = GetDateFormat(LOCALE_USER_DEFAULT, DATE_SHORTDATE, NULL, NULL, ret, retlen);
983
984 if ( !size )
985 return NULL;
986 return ret;
987 }
988
989 /* %RANDOM% */
990 else if (_tcsicmp(varName,_T("random")) ==0)
991 {
992 if ( !GrowIfNecessary ( MAX_PATH, &ret, &retlen ) )
993 return NULL;
994 /* Get random number */
995 _itot(rand(),ret,10);
996 return ret;
997 }
998
999 /* %CMDCMDLINE% */
1000 else if (_tcsicmp(varName,_T("cmdcmdline")) ==0)
1001 {
1002 return GetCommandLine();
1003 }
1004
1005 /* %CMDEXTVERSION% */
1006 else if (_tcsicmp(varName,_T("cmdextversion")) ==0)
1007 {
1008 if ( !GrowIfNecessary ( MAX_PATH, &ret, &retlen ) )
1009 return NULL;
1010 /* Set version number to 2 */
1011 _itot(2,ret,10);
1012 return ret;
1013 }
1014
1015 /* %ERRORLEVEL% */
1016 else if (_tcsicmp(varName,_T("errorlevel")) ==0)
1017 {
1018 if ( !GrowIfNecessary ( MAX_PATH, &ret, &retlen ) )
1019 return NULL;
1020 _itot(nErrorLevel,ret,10);
1021 return ret;
1022 }
1023
1024 return NULL;
1025 }
1026
1027
1028
1029 LPCTSTR
1030 GetBatchVar ( LPCTSTR varName, UINT* varNameLen )
1031 {
1032 static LPTSTR ret = NULL;
1033 static UINT retlen = 0;
1034 DWORD len;
1035
1036 *varNameLen = 1;
1037
1038 switch ( *varName )
1039 {
1040 case _T('~'):
1041 varName++;
1042 if (_tcsncicmp(varName, _T("dp0"), 3) == 0)
1043 {
1044 *varNameLen = 4;
1045 len = _tcsrchr(bc->BatchFilePath, _T('\\')) + 1 - bc->BatchFilePath;
1046 if (!GrowIfNecessary(len + 1, &ret, &retlen))
1047 return NULL;
1048 memcpy(ret, bc->BatchFilePath, len * sizeof(TCHAR));
1049 ret[len] = _T('\0');
1050 return ret;
1051 }
1052
1053 *varNameLen = 2;
1054 if (*varName >= _T('0') && *varName <= _T('9')) {
1055 LPTSTR arg = FindArg(*varName - _T('0'));
1056
1057 if (*arg != _T('"'))
1058 return arg;
1059
1060 /* Exclude the leading and trailing quotes */
1061 arg++;
1062 len = _tcslen(arg);
1063 if (arg[len - 1] == _T('"'))
1064 len--;
1065
1066 if (!GrowIfNecessary(len + 1, &ret, &retlen))
1067 return NULL;
1068 memcpy(ret, arg, len * sizeof(TCHAR));
1069 ret[len] = _T('\0');
1070 return ret;
1071 }
1072 break;
1073 case _T('0'):
1074 case _T('1'):
1075 case _T('2'):
1076 case _T('3'):
1077 case _T('4'):
1078 case _T('5'):
1079 case _T('6'):
1080 case _T('7'):
1081 case _T('8'):
1082 case _T('9'):
1083 return FindArg(*varName - _T('0'));
1084
1085 case _T('*'):
1086 //
1087 // Copy over the raw params(not including the batch file name
1088 //
1089 return bc->raw_params;
1090
1091 case _T('%'):
1092 return _T("%");
1093 }
1094 return NULL;
1095 }
1096
1097 BOOL
1098 SubstituteVars(TCHAR *Src, TCHAR *Dest, TCHAR Delim, BOOL bIsBatch)
1099 {
1100 #define APPEND(From, Length) { \
1101 if (Dest + (Length) > DestEnd) \
1102 goto too_long; \
1103 memcpy(Dest, From, (Length) * sizeof(TCHAR)); \
1104 Dest += Length; }
1105 #define APPEND1(Char) { \
1106 if (Dest >= DestEnd) \
1107 goto too_long; \
1108 *Dest++ = Char; }
1109
1110 TCHAR *DestEnd = Dest + CMDLINE_LENGTH - 1;
1111 const TCHAR *Var;
1112 int VarLength;
1113 TCHAR *SubstStart;
1114 TCHAR EndChr;
1115 while (*Src)
1116 {
1117 if (*Src != Delim)
1118 {
1119 APPEND1(*Src++)
1120 continue;
1121 }
1122
1123 Src++;
1124 if (bIsBatch && Delim == _T('%'))
1125 {
1126 UINT NameLen;
1127 Var = GetBatchVar(Src, &NameLen);
1128 if (Var != NULL)
1129 {
1130 VarLength = _tcslen(Var);
1131 APPEND(Var, VarLength)
1132 Src += NameLen;
1133 continue;
1134 }
1135 }
1136
1137 /* Find the end of the variable name. A colon (:) will usually
1138 * end the name and begin the optional modifier, but not if it
1139 * is immediately followed by the delimiter (%VAR:%). */
1140 SubstStart = Src;
1141 while (*Src != Delim && !(*Src == _T(':') && Src[1] != Delim))
1142 {
1143 if (!*Src)
1144 goto bad_subst;
1145 Src++;
1146 }
1147
1148 EndChr = *Src;
1149 *Src = _T('\0');
1150 Var = GetEnvVarOrSpecial(SubstStart);
1151 *Src++ = EndChr;
1152 if (Var == NULL)
1153 {
1154 /* In a batch file, %NONEXISTENT% "expands" to an empty string */
1155 if (bIsBatch)
1156 continue;
1157 goto bad_subst;
1158 }
1159 VarLength = _tcslen(Var);
1160
1161 if (EndChr == Delim)
1162 {
1163 /* %VAR% - use as-is */
1164 APPEND(Var, VarLength)
1165 }
1166 else if (*Src == _T('~'))
1167 {
1168 /* %VAR:~[start][,length]% - substring
1169 * Negative values are offsets from the end */
1170 int Start = _tcstol(Src + 1, &Src, 0);
1171 int End = VarLength;
1172 if (Start < 0)
1173 Start += VarLength;
1174 Start = max(Start, 0);
1175 Start = min(Start, VarLength);
1176 if (*Src == _T(','))
1177 {
1178 End = _tcstol(Src + 1, &Src, 0);
1179 End += (End < 0) ? VarLength : Start;
1180 End = max(End, Start);
1181 End = min(End, VarLength);
1182 }
1183 if (*Src++ != Delim)
1184 goto bad_subst;
1185 APPEND(&Var[Start], End - Start);
1186 }
1187 else
1188 {
1189 /* %VAR:old=new% - replace all occurrences of old with new
1190 * %VAR:*old=new% - replace first occurrence only,
1191 * and remove everything before it */
1192 TCHAR *Old, *New;
1193 DWORD OldLength, NewLength;
1194 BOOL Star = FALSE;
1195 int LastMatch = 0, i = 0;
1196
1197 if (*Src == _T('*'))
1198 {
1199 Star = TRUE;
1200 Src++;
1201 }
1202
1203 /* the string to replace may contain the delimiter */
1204 Src = _tcschr(Old = Src, _T('='));
1205 if (Src == NULL)
1206 goto bad_subst;
1207 OldLength = Src++ - Old;
1208 if (OldLength == 0)
1209 goto bad_subst;
1210
1211 Src = _tcschr(New = Src, Delim);
1212 if (Src == NULL)
1213 goto bad_subst;
1214 NewLength = Src++ - New;
1215
1216 while (i < VarLength)
1217 {
1218 if (_tcsnicmp(&Var[i], Old, OldLength) == 0)
1219 {
1220 if (!Star)
1221 APPEND(&Var[LastMatch], i - LastMatch)
1222 APPEND(New, NewLength)
1223 i += OldLength;
1224 LastMatch = i;
1225 if (Star)
1226 break;
1227 continue;
1228 }
1229 i++;
1230 }
1231 APPEND(&Var[LastMatch], VarLength - LastMatch)
1232 }
1233 continue;
1234
1235 bad_subst:
1236 Src = SubstStart;
1237 if (!bIsBatch)
1238 APPEND1(Delim)
1239 }
1240 *Dest = _T('\0');
1241 return TRUE;
1242 too_long:
1243 ConOutResPrintf(STRING_ALIAS_ERROR);
1244 nErrorLevel = 9023;
1245 return FALSE;
1246 #undef APPEND
1247 #undef APPEND1
1248 }
1249
1250
1251 /*
1252 * do the prompt/input/process loop
1253 *
1254 */
1255
1256 BOOL bNoInteractive;
1257 BOOL bIsBatch;
1258
1259 BOOL
1260 ReadLine (TCHAR *commandline, BOOL bMore)
1261 {
1262 TCHAR readline[CMDLINE_LENGTH];
1263 LPTSTR ip;
1264
1265 /* if no batch input then... */
1266 if (!(ip = ReadBatchLine()))
1267 {
1268 if (bNoInteractive)
1269 {
1270 bExit = TRUE;
1271 return FALSE;
1272 }
1273
1274 if (bMore)
1275 {
1276 ConOutPrintf(_T("More? "));
1277 }
1278 else
1279 {
1280 /* JPP 19980807 - if echo off, don't print prompt */
1281 if (bEcho)
1282 PrintPrompt();
1283 }
1284
1285 ReadCommand (readline, CMDLINE_LENGTH - 1);
1286 if (CheckCtrlBreak(BREAK_INPUT))
1287 {
1288 ConOutPuts(_T("\n"));
1289 return FALSE;
1290 }
1291 ip = readline;
1292 bIsBatch = FALSE;
1293 }
1294 else
1295 {
1296 bIsBatch = TRUE;
1297 }
1298
1299 if (!SubstituteVars(ip, commandline, _T('%'), bIsBatch))
1300 return FALSE;
1301
1302 /* FIXME: !vars! should be substituted later, after parsing. */
1303 if (!SubstituteVars(commandline, readline, _T('!'), bIsBatch))
1304 return FALSE;
1305 _tcscpy(commandline, readline);
1306
1307 return TRUE;
1308 }
1309
1310 static INT
1311 ProcessInput (BOOL bFlag)
1312 {
1313 PARSED_COMMAND *Cmd;
1314
1315 bNoInteractive = bFlag;
1316 do
1317 {
1318 Cmd = ParseCommand(NULL);
1319 if (!Cmd)
1320 continue;
1321
1322 /* JPP 19980807 */
1323 /* Echo batch file line */
1324 if (bIsBatch && bEcho && Cmd->Type != C_QUIET)
1325 {
1326 PrintPrompt ();
1327 EchoCommand(Cmd);
1328 ConOutChar(_T('\n'));
1329 }
1330
1331 ExecuteCommand(Cmd);
1332 if (bEcho && !bIgnoreEcho && (!bIsBatch || Cmd->Type != C_QUIET))
1333 ConOutChar ('\n');
1334 FreeCommand(Cmd);
1335 bIgnoreEcho = FALSE;
1336 }
1337 while (!bCanExit || !bExit);
1338
1339 return nErrorLevel;
1340 }
1341
1342
1343 /*
1344 * control-break handler.
1345 */
1346 BOOL WINAPI BreakHandler (DWORD dwCtrlType)
1347 {
1348
1349 DWORD dwWritten;
1350 INPUT_RECORD rec;
1351 static BOOL SelfGenerated = FALSE;
1352
1353 if ((dwCtrlType != CTRL_C_EVENT) &&
1354 (dwCtrlType != CTRL_BREAK_EVENT))
1355 {
1356 return FALSE;
1357 }
1358 else
1359 {
1360 if(SelfGenerated)
1361 {
1362 SelfGenerated = FALSE;
1363 return TRUE;
1364 }
1365 }
1366
1367 if (bChildProcessRunning == TRUE)
1368 {
1369 SelfGenerated = TRUE;
1370 GenerateConsoleCtrlEvent (dwCtrlType, 0);
1371 return TRUE;
1372 }
1373
1374
1375 rec.EventType = KEY_EVENT;
1376 rec.Event.KeyEvent.bKeyDown = TRUE;
1377 rec.Event.KeyEvent.wRepeatCount = 1;
1378 rec.Event.KeyEvent.wVirtualKeyCode = _T('C');
1379 rec.Event.KeyEvent.wVirtualScanCode = _T('C') - 35;
1380 rec.Event.KeyEvent.uChar.AsciiChar = _T('C');
1381 rec.Event.KeyEvent.uChar.UnicodeChar = _T('C');
1382 rec.Event.KeyEvent.dwControlKeyState = RIGHT_CTRL_PRESSED;
1383
1384 WriteConsoleInput(
1385 hIn,
1386 &rec,
1387 1,
1388 &dwWritten);
1389
1390 bCtrlBreak = TRUE;
1391 /* FIXME: Handle batch files */
1392
1393 //ConOutPrintf(_T("^C"));
1394
1395
1396 return TRUE;
1397 }
1398
1399
1400 VOID AddBreakHandler (VOID)
1401 {
1402 SetConsoleCtrlHandler ((PHANDLER_ROUTINE)BreakHandler, TRUE);
1403 }
1404
1405
1406 VOID RemoveBreakHandler (VOID)
1407 {
1408 SetConsoleCtrlHandler ((PHANDLER_ROUTINE)BreakHandler, FALSE);
1409 }
1410
1411
1412 /*
1413 * show commands and options that are available.
1414 *
1415 */
1416 #if 0
1417 static VOID
1418 ShowCommands (VOID)
1419 {
1420 /* print command list */
1421 ConOutResPuts(STRING_CMD_HELP1);
1422 PrintCommandList();
1423
1424 /* print feature list */
1425 ConOutResPuts(STRING_CMD_HELP2);
1426
1427 #ifdef FEATURE_ALIASES
1428 ConOutResPuts(STRING_CMD_HELP3);
1429 #endif
1430 #ifdef FEATURE_HISTORY
1431 ConOutResPuts(STRING_CMD_HELP4);
1432 #endif
1433 #ifdef FEATURE_UNIX_FILENAME_COMPLETION
1434 ConOutResPuts(STRING_CMD_HELP5);
1435 #endif
1436 #ifdef FEATURE_DIRECTORY_STACK
1437 ConOutResPuts(STRING_CMD_HELP6);
1438 #endif
1439 #ifdef FEATURE_REDIRECTION
1440 ConOutResPuts(STRING_CMD_HELP7);
1441 #endif
1442 ConOutChar(_T('\n'));
1443 }
1444 #endif
1445
1446 static VOID
1447 ExecuteAutoRunFile (VOID)
1448 {
1449 TCHAR autorun[MAX_PATH];
1450 DWORD len = MAX_PATH;
1451 HKEY hkey;
1452
1453 if( RegOpenKeyEx(HKEY_LOCAL_MACHINE,
1454 _T("SOFTWARE\\Microsoft\\Command Processor"),
1455 0,
1456 KEY_READ,
1457 &hkey ) == ERROR_SUCCESS)
1458 {
1459 if(RegQueryValueEx(hkey,
1460 _T("AutoRun"),
1461 0,
1462 0,
1463 (LPBYTE)autorun,
1464 &len) == ERROR_SUCCESS)
1465 {
1466 ParseCommandLine (autorun);
1467 }
1468 }
1469
1470 RegCloseKey(hkey);
1471 }
1472
1473 /*
1474 * set up global initializations and process parameters
1475 *
1476 * argc - number of parameters to command.com
1477 * argv - command-line parameters
1478 *
1479 */
1480 static VOID
1481 Initialize (int argc, const TCHAR* argv[])
1482 {
1483 TCHAR commandline[CMDLINE_LENGTH];
1484 TCHAR ModuleName[_MAX_PATH + 1];
1485 INT i;
1486 TCHAR lpBuffer[2];
1487
1488 //INT len;
1489 //TCHAR *ptr, *cmdLine;
1490
1491 /* get version information */
1492 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1493 GetVersionEx (&osvi);
1494
1495 /* Some people like to run ReactOS cmd.exe on Win98, it helps in the
1496 * build process. So don't link implicitly against ntdll.dll, load it
1497 * dynamically instead */
1498
1499 if (osvi.dwPlatformId == VER_PLATFORM_WIN32_NT)
1500 {
1501 /* ntdll is always present on NT */
1502 NtDllModule = GetModuleHandle(TEXT("ntdll.dll"));
1503 }
1504 else
1505 {
1506 /* not all 9x versions have a ntdll.dll, try to load it */
1507 NtDllModule = LoadLibrary(TEXT("ntdll.dll"));
1508 }
1509
1510 if (NtDllModule != NULL)
1511 {
1512 NtQueryInformationProcessPtr = (NtQueryInformationProcessProc)GetProcAddress(NtDllModule, "NtQueryInformationProcess");
1513 NtReadVirtualMemoryPtr = (NtReadVirtualMemoryProc)GetProcAddress(NtDllModule, "NtReadVirtualMemory");
1514 }
1515
1516
1517 TRACE ("[command args:\n");
1518 for (i = 0; i < argc; i++)
1519 {
1520 TRACE ("%d. %s\n", i, debugstr_aw(argv[i]));
1521 }
1522 TRACE ("]\n");
1523
1524 InitLocale ();
1525
1526 /* get default input and output console handles */
1527 hOut = GetStdHandle (STD_OUTPUT_HANDLE);
1528 hIn = GetStdHandle (STD_INPUT_HANDLE);
1529
1530 /* Set EnvironmentVariable PROMPT if it does not exists any env value.
1531 for you can change the EnvirommentVariable for prompt before cmd start
1532 this patch are not 100% right, if it does not exists a PROMPT value cmd should use
1533 $P$G as defualt not set EnvirommentVariable PROMPT to $P$G if it does not exists */
1534 if (GetEnvironmentVariable(_T("PROMPT"),lpBuffer, sizeof(lpBuffer) / sizeof(lpBuffer[0])) == 0)
1535 SetEnvironmentVariable (_T("PROMPT"), _T("$P$G"));
1536
1537
1538 if (argc >= 2 && !_tcsncmp (argv[1], _T("/?"), 2))
1539 {
1540 ConOutResPaging(TRUE,STRING_CMD_HELP8);
1541 cmd_exit(0);
1542 }
1543 SetConsoleMode (hIn, ENABLE_PROCESSED_INPUT);
1544
1545 #ifdef INCLUDE_CMD_CHDIR
1546 InitLastPath ();
1547 #endif
1548
1549 if (argc >= 2)
1550 {
1551 for (i = 1; i < argc; i++)
1552 {
1553 if (!_tcsicmp (argv[i], _T("/p")))
1554 {
1555 if (!IsExistingFile (_T("\\autoexec.bat")))
1556 {
1557 #ifdef INCLUDE_CMD_DATE
1558 cmd_date (_T(""));
1559 #endif
1560 #ifdef INCLUDE_CMD_TIME
1561 cmd_time (_T(""));
1562 #endif
1563 }
1564 else
1565 {
1566 ParseCommandLine (_T("\\autoexec.bat"));
1567 }
1568 bCanExit = FALSE;
1569 }
1570 else if (!_tcsicmp (argv[i], _T("/c")))
1571 {
1572 /* This just runs a program and exits */
1573 ++i;
1574 if (i < argc)
1575 {
1576 _tcscpy (commandline, argv[i]);
1577 while (++i < argc)
1578 {
1579 _tcscat (commandline, _T(" "));
1580 _tcscat (commandline, argv[i]);
1581 }
1582
1583 ParseCommandLine(commandline);
1584 cmd_exit (ProcessInput (TRUE));
1585 }
1586 else
1587 {
1588 cmd_exit (0);
1589 }
1590 }
1591 else if (!_tcsicmp (argv[i], _T("/k")))
1592 {
1593 /* This just runs a program and remains */
1594 ++i;
1595 if (i < argc)
1596 {
1597 _tcscpy (commandline, _T("\""));
1598 _tcscat (commandline, argv[i]);
1599 _tcscat (commandline, _T("\""));
1600 while (++i < argc)
1601 {
1602 _tcscat (commandline, _T(" "));
1603 _tcscat (commandline, argv[i]);
1604 }
1605 ParseCommandLine(commandline);
1606 }
1607 }
1608 #ifdef INCLUDE_CMD_COLOR
1609 else if (!_tcsnicmp (argv[i], _T("/t:"), 3))
1610 {
1611 /* process /t (color) argument */
1612 wDefColor = (WORD)_tcstoul (&argv[i][3], NULL, 16);
1613 wColor = wDefColor;
1614 SetScreenColor (wColor, TRUE);
1615 }
1616 #endif
1617 }
1618 }
1619 else
1620 {
1621 /* Display a simple version string */
1622 ConOutPrintf(_T("ReactOS Operating System [Version %s-%s]\n"),
1623 _T(KERNEL_RELEASE_STR),
1624 _T(KERNEL_VERSION_BUILD_STR));
1625
1626 ConOutPuts (_T("(C) Copyright 1998-") _T(COPYRIGHT_YEAR) _T(" ReactOS Team.\n"));
1627 }
1628
1629 ExecuteAutoRunFile ();
1630
1631 #ifdef FEATURE_DIR_STACK
1632 /* initialize directory stack */
1633 InitDirectoryStack ();
1634 #endif
1635
1636
1637 #ifdef FEATURE_HISTORY
1638 /*initialize history*/
1639 InitHistory();
1640 #endif
1641
1642 /* Set COMSPEC environment variable */
1643 if (0 != GetModuleFileName (NULL, ModuleName, _MAX_PATH + 1))
1644 {
1645 ModuleName[_MAX_PATH] = _T('\0');
1646 SetEnvironmentVariable (_T("COMSPEC"), ModuleName);
1647 }
1648
1649 /* add ctrl break handler */
1650 AddBreakHandler ();
1651 }
1652
1653
1654 static VOID Cleanup (int argc, const TCHAR *argv[])
1655 {
1656 /* run cmdexit.bat */
1657 if (IsExistingFile (_T("cmdexit.bat")))
1658 {
1659 ConErrResPuts(STRING_CMD_ERROR5);
1660
1661 ParseCommandLine (_T("cmdexit.bat"));
1662 }
1663 else if (IsExistingFile (_T("\\cmdexit.bat")))
1664 {
1665 ConErrResPuts (STRING_CMD_ERROR5);
1666 ParseCommandLine (_T("\\cmdexit.bat"));
1667 }
1668
1669 #ifdef FEATURE_DIECTORY_STACK
1670 /* destroy directory stack */
1671 DestroyDirectoryStack ();
1672 #endif
1673
1674 #ifdef INCLUDE_CMD_CHDIR
1675 FreeLastPath ();
1676 #endif
1677
1678 #ifdef FEATURE_HISTORY
1679 CleanHistory();
1680 #endif
1681
1682
1683 /* remove ctrl break handler */
1684 RemoveBreakHandler ();
1685 SetConsoleMode( GetStdHandle( STD_INPUT_HANDLE ),
1686 ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT | ENABLE_ECHO_INPUT );
1687
1688 if (NtDllModule != NULL)
1689 {
1690 FreeLibrary(NtDllModule);
1691 }
1692 }
1693
1694 /*
1695 * main function
1696 */
1697 int cmd_main (int argc, const TCHAR *argv[])
1698 {
1699 TCHAR startPath[MAX_PATH];
1700 CONSOLE_SCREEN_BUFFER_INFO Info;
1701 INT nExitCode;
1702
1703 GetCurrentDirectory(MAX_PATH,startPath);
1704 _tchdir(startPath);
1705
1706 SetFileApisToOEM();
1707 InputCodePage= 0;
1708 OutputCodePage = 0;
1709
1710 hConsole = CreateFile(_T("CONOUT$"), GENERIC_READ|GENERIC_WRITE,
1711 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL,
1712 OPEN_EXISTING, 0, NULL);
1713 if (GetConsoleScreenBufferInfo(hConsole, &Info) == FALSE)
1714 {
1715 ConErrFormatMessage(GetLastError());
1716 return(1);
1717 }
1718 wColor = Info.wAttributes;
1719 wDefColor = wColor;
1720
1721 InputCodePage= GetConsoleCP();
1722 OutputCodePage = GetConsoleOutputCP();
1723 CMD_ModuleHandle = GetModuleHandle(NULL);
1724
1725 /* check switches on command-line */
1726 Initialize(argc, argv);
1727
1728 /* call prompt routine */
1729 nExitCode = ProcessInput(FALSE);
1730
1731 /* do the cleanup */
1732 Cleanup(argc, argv);
1733
1734 cmd_exit(nExitCode);
1735 return(nExitCode);
1736 }
1737
1738 /* EOF */