sync to trunk r38300
[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 0x%p\n", 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->Command.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 case C_IF:
907 Success = ExecuteIf(Cmd);
908 break;
909 }
910
911 UndoRedirection(Cmd->Redirections, NULL);
912 return Success;
913 }
914
915 BOOL
916 GrowIfNecessary_dbg ( UINT needed, LPTSTR* ret, UINT* retlen, const char *file, int line )
917 {
918 if ( *ret && needed < *retlen )
919 return TRUE;
920 *retlen = needed;
921 if ( *ret )
922 cmd_free ( *ret );
923 #ifdef _DEBUG_MEM
924 *ret = (LPTSTR)cmd_alloc_dbg ( *retlen * sizeof(TCHAR), file, line );
925 #else
926 *ret = (LPTSTR)cmd_alloc ( *retlen * sizeof(TCHAR) );
927 #endif
928 if ( !*ret )
929 SetLastError ( ERROR_OUTOFMEMORY );
930 return *ret != NULL;
931 }
932 #define GrowIfNecessary(x, y, z) GrowIfNecessary_dbg(x, y, z, __FILE__, __LINE__)
933
934 LPCTSTR
935 GetEnvVarOrSpecial ( LPCTSTR varName )
936 {
937 static LPTSTR ret = NULL;
938 static UINT retlen = 0;
939 UINT size;
940
941 size = GetEnvironmentVariable ( varName, ret, retlen );
942 if ( size > retlen )
943 {
944 if ( !GrowIfNecessary ( size, &ret, &retlen ) )
945 return NULL;
946 size = GetEnvironmentVariable ( varName, ret, retlen );
947 }
948 if ( size )
949 return ret;
950
951 /* env var doesn't exist, look for a "special" one */
952 /* %CD% */
953 if (_tcsicmp(varName,_T("cd")) ==0)
954 {
955 size = GetCurrentDirectory ( retlen, ret );
956 if ( size > retlen )
957 {
958 if ( !GrowIfNecessary ( size, &ret, &retlen ) )
959 return NULL;
960 size = GetCurrentDirectory ( retlen, ret );
961 }
962 if ( !size )
963 return NULL;
964 return ret;
965 }
966 /* %TIME% */
967 else if (_tcsicmp(varName,_T("time")) ==0)
968 {
969 SYSTEMTIME t;
970 if ( !GrowIfNecessary ( MAX_PATH, &ret, &retlen ) )
971 return NULL;
972 GetSystemTime(&t);
973 _sntprintf ( ret, retlen, _T("%02d%c%02d%c%02d%c%02d"),
974 t.wHour, cTimeSeparator, t.wMinute, cTimeSeparator,
975 t.wSecond, cDecimalSeparator, t.wMilliseconds / 10);
976 return ret;
977 }
978 /* %DATE% */
979 else if (_tcsicmp(varName,_T("date")) ==0)
980 {
981
982 if ( !GrowIfNecessary ( GetDateFormat(LOCALE_USER_DEFAULT, DATE_SHORTDATE, NULL, NULL, NULL, 0), &ret, &retlen ) )
983 return NULL;
984
985 size = GetDateFormat(LOCALE_USER_DEFAULT, DATE_SHORTDATE, NULL, NULL, ret, retlen);
986
987 if ( !size )
988 return NULL;
989 return ret;
990 }
991
992 /* %RANDOM% */
993 else if (_tcsicmp(varName,_T("random")) ==0)
994 {
995 if ( !GrowIfNecessary ( MAX_PATH, &ret, &retlen ) )
996 return NULL;
997 /* Get random number */
998 _itot(rand(),ret,10);
999 return ret;
1000 }
1001
1002 /* %CMDCMDLINE% */
1003 else if (_tcsicmp(varName,_T("cmdcmdline")) ==0)
1004 {
1005 return GetCommandLine();
1006 }
1007
1008 /* %CMDEXTVERSION% */
1009 else if (_tcsicmp(varName,_T("cmdextversion")) ==0)
1010 {
1011 if ( !GrowIfNecessary ( MAX_PATH, &ret, &retlen ) )
1012 return NULL;
1013 /* Set version number to 2 */
1014 _itot(2,ret,10);
1015 return ret;
1016 }
1017
1018 /* %ERRORLEVEL% */
1019 else if (_tcsicmp(varName,_T("errorlevel")) ==0)
1020 {
1021 if ( !GrowIfNecessary ( MAX_PATH, &ret, &retlen ) )
1022 return NULL;
1023 _itot(nErrorLevel,ret,10);
1024 return ret;
1025 }
1026
1027 return NULL;
1028 }
1029
1030
1031
1032 LPCTSTR
1033 GetBatchVar ( LPCTSTR varName, UINT* varNameLen )
1034 {
1035 static LPTSTR ret = NULL;
1036 static UINT retlen = 0;
1037 DWORD len;
1038
1039 *varNameLen = 1;
1040
1041 switch ( *varName )
1042 {
1043 case _T('~'):
1044 varName++;
1045 if (_tcsncicmp(varName, _T("dp0"), 3) == 0)
1046 {
1047 *varNameLen = 4;
1048 len = _tcsrchr(bc->BatchFilePath, _T('\\')) + 1 - bc->BatchFilePath;
1049 if (!GrowIfNecessary(len + 1, &ret, &retlen))
1050 return NULL;
1051 memcpy(ret, bc->BatchFilePath, len * sizeof(TCHAR));
1052 ret[len] = _T('\0');
1053 return ret;
1054 }
1055
1056 *varNameLen = 2;
1057 if (*varName >= _T('0') && *varName <= _T('9')) {
1058 LPTSTR arg = FindArg(*varName - _T('0'));
1059
1060 if (*arg != _T('"'))
1061 return arg;
1062
1063 /* Exclude the leading and trailing quotes */
1064 arg++;
1065 len = _tcslen(arg);
1066 if (arg[len - 1] == _T('"'))
1067 len--;
1068
1069 if (!GrowIfNecessary(len + 1, &ret, &retlen))
1070 return NULL;
1071 memcpy(ret, arg, len * sizeof(TCHAR));
1072 ret[len] = _T('\0');
1073 return ret;
1074 }
1075 break;
1076 case _T('0'):
1077 case _T('1'):
1078 case _T('2'):
1079 case _T('3'):
1080 case _T('4'):
1081 case _T('5'):
1082 case _T('6'):
1083 case _T('7'):
1084 case _T('8'):
1085 case _T('9'):
1086 return FindArg(*varName - _T('0'));
1087
1088 case _T('*'):
1089 //
1090 // Copy over the raw params(not including the batch file name
1091 //
1092 return bc->raw_params;
1093
1094 case _T('%'):
1095 return _T("%");
1096 }
1097 return NULL;
1098 }
1099
1100 BOOL
1101 SubstituteVars(TCHAR *Src, TCHAR *Dest, TCHAR Delim, BOOL bIsBatch)
1102 {
1103 #define APPEND(From, Length) { \
1104 if (Dest + (Length) > DestEnd) \
1105 goto too_long; \
1106 memcpy(Dest, From, (Length) * sizeof(TCHAR)); \
1107 Dest += Length; }
1108 #define APPEND1(Char) { \
1109 if (Dest >= DestEnd) \
1110 goto too_long; \
1111 *Dest++ = Char; }
1112
1113 TCHAR *DestEnd = Dest + CMDLINE_LENGTH - 1;
1114 const TCHAR *Var;
1115 int VarLength;
1116 TCHAR *SubstStart;
1117 TCHAR EndChr;
1118 while (*Src)
1119 {
1120 if (*Src != Delim)
1121 {
1122 APPEND1(*Src++)
1123 continue;
1124 }
1125
1126 Src++;
1127 if (bIsBatch && Delim == _T('%'))
1128 {
1129 UINT NameLen;
1130 Var = GetBatchVar(Src, &NameLen);
1131 if (Var != NULL)
1132 {
1133 VarLength = _tcslen(Var);
1134 APPEND(Var, VarLength)
1135 Src += NameLen;
1136 continue;
1137 }
1138 }
1139
1140 /* Find the end of the variable name. A colon (:) will usually
1141 * end the name and begin the optional modifier, but not if it
1142 * is immediately followed by the delimiter (%VAR:%). */
1143 SubstStart = Src;
1144 while (*Src != Delim && !(*Src == _T(':') && Src[1] != Delim))
1145 {
1146 if (!*Src)
1147 goto bad_subst;
1148 Src++;
1149 }
1150
1151 EndChr = *Src;
1152 *Src = _T('\0');
1153 Var = GetEnvVarOrSpecial(SubstStart);
1154 *Src++ = EndChr;
1155 if (Var == NULL)
1156 {
1157 /* In a batch file, %NONEXISTENT% "expands" to an empty string */
1158 if (bIsBatch)
1159 continue;
1160 goto bad_subst;
1161 }
1162 VarLength = _tcslen(Var);
1163
1164 if (EndChr == Delim)
1165 {
1166 /* %VAR% - use as-is */
1167 APPEND(Var, VarLength)
1168 }
1169 else if (*Src == _T('~'))
1170 {
1171 /* %VAR:~[start][,length]% - substring
1172 * Negative values are offsets from the end */
1173 int Start = _tcstol(Src + 1, &Src, 0);
1174 int End = VarLength;
1175 if (Start < 0)
1176 Start += VarLength;
1177 Start = max(Start, 0);
1178 Start = min(Start, VarLength);
1179 if (*Src == _T(','))
1180 {
1181 End = _tcstol(Src + 1, &Src, 0);
1182 End += (End < 0) ? VarLength : Start;
1183 End = max(End, Start);
1184 End = min(End, VarLength);
1185 }
1186 if (*Src++ != Delim)
1187 goto bad_subst;
1188 APPEND(&Var[Start], End - Start);
1189 }
1190 else
1191 {
1192 /* %VAR:old=new% - replace all occurrences of old with new
1193 * %VAR:*old=new% - replace first occurrence only,
1194 * and remove everything before it */
1195 TCHAR *Old, *New;
1196 DWORD OldLength, NewLength;
1197 BOOL Star = FALSE;
1198 int LastMatch = 0, i = 0;
1199
1200 if (*Src == _T('*'))
1201 {
1202 Star = TRUE;
1203 Src++;
1204 }
1205
1206 /* the string to replace may contain the delimiter */
1207 Src = _tcschr(Old = Src, _T('='));
1208 if (Src == NULL)
1209 goto bad_subst;
1210 OldLength = Src++ - Old;
1211 if (OldLength == 0)
1212 goto bad_subst;
1213
1214 Src = _tcschr(New = Src, Delim);
1215 if (Src == NULL)
1216 goto bad_subst;
1217 NewLength = Src++ - New;
1218
1219 while (i < VarLength)
1220 {
1221 if (_tcsnicmp(&Var[i], Old, OldLength) == 0)
1222 {
1223 if (!Star)
1224 APPEND(&Var[LastMatch], i - LastMatch)
1225 APPEND(New, NewLength)
1226 i += OldLength;
1227 LastMatch = i;
1228 if (Star)
1229 break;
1230 continue;
1231 }
1232 i++;
1233 }
1234 APPEND(&Var[LastMatch], VarLength - LastMatch)
1235 }
1236 continue;
1237
1238 bad_subst:
1239 Src = SubstStart;
1240 if (!bIsBatch)
1241 APPEND1(Delim)
1242 }
1243 *Dest = _T('\0');
1244 return TRUE;
1245 too_long:
1246 ConOutResPrintf(STRING_ALIAS_ERROR);
1247 nErrorLevel = 9023;
1248 return FALSE;
1249 #undef APPEND
1250 #undef APPEND1
1251 }
1252
1253
1254 /*
1255 * do the prompt/input/process loop
1256 *
1257 */
1258
1259 BOOL bNoInteractive;
1260 BOOL bIsBatch;
1261
1262 BOOL
1263 ReadLine (TCHAR *commandline, BOOL bMore)
1264 {
1265 TCHAR readline[CMDLINE_LENGTH];
1266 LPTSTR ip;
1267
1268 /* if no batch input then... */
1269 if (!(ip = ReadBatchLine()))
1270 {
1271 if (bNoInteractive)
1272 {
1273 bExit = TRUE;
1274 return FALSE;
1275 }
1276
1277 if (bMore)
1278 {
1279 ConOutPrintf(_T("More? "));
1280 }
1281 else
1282 {
1283 /* JPP 19980807 - if echo off, don't print prompt */
1284 if (bEcho)
1285 PrintPrompt();
1286 }
1287
1288 ReadCommand (readline, CMDLINE_LENGTH - 1);
1289 if (CheckCtrlBreak(BREAK_INPUT))
1290 {
1291 ConOutPuts(_T("\n"));
1292 return FALSE;
1293 }
1294 ip = readline;
1295 bIsBatch = FALSE;
1296 }
1297 else
1298 {
1299 bIsBatch = TRUE;
1300 }
1301
1302 if (!SubstituteVars(ip, commandline, _T('%'), bIsBatch))
1303 return FALSE;
1304
1305 /* FIXME: !vars! should be substituted later, after parsing. */
1306 if (!SubstituteVars(commandline, readline, _T('!'), bIsBatch))
1307 return FALSE;
1308 _tcscpy(commandline, readline);
1309
1310 return TRUE;
1311 }
1312
1313 static INT
1314 ProcessInput (BOOL bFlag)
1315 {
1316 PARSED_COMMAND *Cmd;
1317
1318 bNoInteractive = bFlag;
1319 do
1320 {
1321 Cmd = ParseCommand(NULL);
1322 if (!Cmd)
1323 continue;
1324
1325 /* JPP 19980807 */
1326 /* Echo batch file line */
1327 if (bIsBatch && bEcho && Cmd->Type != C_QUIET)
1328 {
1329 PrintPrompt ();
1330 EchoCommand(Cmd);
1331 ConOutChar(_T('\n'));
1332 }
1333
1334 ExecuteCommand(Cmd);
1335 if (bEcho && !bIgnoreEcho && (!bIsBatch || Cmd->Type != C_QUIET))
1336 ConOutChar ('\n');
1337 FreeCommand(Cmd);
1338 bIgnoreEcho = FALSE;
1339 }
1340 while (!bCanExit || !bExit);
1341
1342 return nErrorLevel;
1343 }
1344
1345
1346 /*
1347 * control-break handler.
1348 */
1349 BOOL WINAPI BreakHandler (DWORD dwCtrlType)
1350 {
1351
1352 DWORD dwWritten;
1353 INPUT_RECORD rec;
1354 static BOOL SelfGenerated = FALSE;
1355
1356 if ((dwCtrlType != CTRL_C_EVENT) &&
1357 (dwCtrlType != CTRL_BREAK_EVENT))
1358 {
1359 return FALSE;
1360 }
1361 else
1362 {
1363 if(SelfGenerated)
1364 {
1365 SelfGenerated = FALSE;
1366 return TRUE;
1367 }
1368 }
1369
1370 if (bChildProcessRunning == TRUE)
1371 {
1372 SelfGenerated = TRUE;
1373 GenerateConsoleCtrlEvent (dwCtrlType, 0);
1374 return TRUE;
1375 }
1376
1377
1378 rec.EventType = KEY_EVENT;
1379 rec.Event.KeyEvent.bKeyDown = TRUE;
1380 rec.Event.KeyEvent.wRepeatCount = 1;
1381 rec.Event.KeyEvent.wVirtualKeyCode = _T('C');
1382 rec.Event.KeyEvent.wVirtualScanCode = _T('C') - 35;
1383 rec.Event.KeyEvent.uChar.AsciiChar = _T('C');
1384 rec.Event.KeyEvent.uChar.UnicodeChar = _T('C');
1385 rec.Event.KeyEvent.dwControlKeyState = RIGHT_CTRL_PRESSED;
1386
1387 WriteConsoleInput(
1388 hIn,
1389 &rec,
1390 1,
1391 &dwWritten);
1392
1393 bCtrlBreak = TRUE;
1394 /* FIXME: Handle batch files */
1395
1396 //ConOutPrintf(_T("^C"));
1397
1398
1399 return TRUE;
1400 }
1401
1402
1403 VOID AddBreakHandler (VOID)
1404 {
1405 SetConsoleCtrlHandler ((PHANDLER_ROUTINE)BreakHandler, TRUE);
1406 }
1407
1408
1409 VOID RemoveBreakHandler (VOID)
1410 {
1411 SetConsoleCtrlHandler ((PHANDLER_ROUTINE)BreakHandler, FALSE);
1412 }
1413
1414
1415 /*
1416 * show commands and options that are available.
1417 *
1418 */
1419 #if 0
1420 static VOID
1421 ShowCommands (VOID)
1422 {
1423 /* print command list */
1424 ConOutResPuts(STRING_CMD_HELP1);
1425 PrintCommandList();
1426
1427 /* print feature list */
1428 ConOutResPuts(STRING_CMD_HELP2);
1429
1430 #ifdef FEATURE_ALIASES
1431 ConOutResPuts(STRING_CMD_HELP3);
1432 #endif
1433 #ifdef FEATURE_HISTORY
1434 ConOutResPuts(STRING_CMD_HELP4);
1435 #endif
1436 #ifdef FEATURE_UNIX_FILENAME_COMPLETION
1437 ConOutResPuts(STRING_CMD_HELP5);
1438 #endif
1439 #ifdef FEATURE_DIRECTORY_STACK
1440 ConOutResPuts(STRING_CMD_HELP6);
1441 #endif
1442 #ifdef FEATURE_REDIRECTION
1443 ConOutResPuts(STRING_CMD_HELP7);
1444 #endif
1445 ConOutChar(_T('\n'));
1446 }
1447 #endif
1448
1449 static VOID
1450 ExecuteAutoRunFile (VOID)
1451 {
1452 TCHAR autorun[MAX_PATH];
1453 DWORD len = MAX_PATH;
1454 HKEY hkey;
1455
1456 if( RegOpenKeyEx(HKEY_LOCAL_MACHINE,
1457 _T("SOFTWARE\\Microsoft\\Command Processor"),
1458 0,
1459 KEY_READ,
1460 &hkey ) == ERROR_SUCCESS)
1461 {
1462 if(RegQueryValueEx(hkey,
1463 _T("AutoRun"),
1464 0,
1465 0,
1466 (LPBYTE)autorun,
1467 &len) == ERROR_SUCCESS)
1468 {
1469 ParseCommandLine (autorun);
1470 }
1471 }
1472
1473 RegCloseKey(hkey);
1474 }
1475
1476 /*
1477 * set up global initializations and process parameters
1478 *
1479 * argc - number of parameters to command.com
1480 * argv - command-line parameters
1481 *
1482 */
1483 static VOID
1484 Initialize (int argc, const TCHAR* argv[])
1485 {
1486 TCHAR commandline[CMDLINE_LENGTH];
1487 TCHAR ModuleName[_MAX_PATH + 1];
1488 INT i;
1489 TCHAR lpBuffer[2];
1490
1491 //INT len;
1492 //TCHAR *ptr, *cmdLine;
1493
1494 /* get version information */
1495 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1496 GetVersionEx (&osvi);
1497
1498 /* Some people like to run ReactOS cmd.exe on Win98, it helps in the
1499 * build process. So don't link implicitly against ntdll.dll, load it
1500 * dynamically instead */
1501
1502 if (osvi.dwPlatformId == VER_PLATFORM_WIN32_NT)
1503 {
1504 /* ntdll is always present on NT */
1505 NtDllModule = GetModuleHandle(TEXT("ntdll.dll"));
1506 }
1507 else
1508 {
1509 /* not all 9x versions have a ntdll.dll, try to load it */
1510 NtDllModule = LoadLibrary(TEXT("ntdll.dll"));
1511 }
1512
1513 if (NtDllModule != NULL)
1514 {
1515 NtQueryInformationProcessPtr = (NtQueryInformationProcessProc)GetProcAddress(NtDllModule, "NtQueryInformationProcess");
1516 NtReadVirtualMemoryPtr = (NtReadVirtualMemoryProc)GetProcAddress(NtDllModule, "NtReadVirtualMemory");
1517 }
1518
1519
1520 TRACE ("[command args:\n");
1521 for (i = 0; i < argc; i++)
1522 {
1523 TRACE ("%d. %s\n", i, debugstr_aw(argv[i]));
1524 }
1525 TRACE ("]\n");
1526
1527 InitLocale ();
1528
1529 /* get default input and output console handles */
1530 hOut = GetStdHandle (STD_OUTPUT_HANDLE);
1531 hIn = GetStdHandle (STD_INPUT_HANDLE);
1532
1533 /* Set EnvironmentVariable PROMPT if it does not exists any env value.
1534 for you can change the EnvirommentVariable for prompt before cmd start
1535 this patch are not 100% right, if it does not exists a PROMPT value cmd should use
1536 $P$G as defualt not set EnvirommentVariable PROMPT to $P$G if it does not exists */
1537 if (GetEnvironmentVariable(_T("PROMPT"),lpBuffer, sizeof(lpBuffer) / sizeof(lpBuffer[0])) == 0)
1538 SetEnvironmentVariable (_T("PROMPT"), _T("$P$G"));
1539
1540
1541 if (argc >= 2 && !_tcsncmp (argv[1], _T("/?"), 2))
1542 {
1543 ConOutResPaging(TRUE,STRING_CMD_HELP8);
1544 cmd_exit(0);
1545 }
1546 SetConsoleMode (hIn, ENABLE_PROCESSED_INPUT);
1547
1548 #ifdef INCLUDE_CMD_CHDIR
1549 InitLastPath ();
1550 #endif
1551
1552 if (argc >= 2)
1553 {
1554 for (i = 1; i < argc; i++)
1555 {
1556 if (!_tcsicmp (argv[i], _T("/p")))
1557 {
1558 if (!IsExistingFile (_T("\\autoexec.bat")))
1559 {
1560 #ifdef INCLUDE_CMD_DATE
1561 cmd_date (_T(""));
1562 #endif
1563 #ifdef INCLUDE_CMD_TIME
1564 cmd_time (_T(""));
1565 #endif
1566 }
1567 else
1568 {
1569 ParseCommandLine (_T("\\autoexec.bat"));
1570 }
1571 bCanExit = FALSE;
1572 }
1573 else if (!_tcsicmp (argv[i], _T("/c")))
1574 {
1575 /* This just runs a program and exits */
1576 ++i;
1577 if (i < argc)
1578 {
1579 _tcscpy (commandline, argv[i]);
1580 while (++i < argc)
1581 {
1582 _tcscat (commandline, _T(" "));
1583 _tcscat (commandline, argv[i]);
1584 }
1585
1586 ParseCommandLine(commandline);
1587 cmd_exit (ProcessInput (TRUE));
1588 }
1589 else
1590 {
1591 cmd_exit (0);
1592 }
1593 }
1594 else if (!_tcsicmp (argv[i], _T("/k")))
1595 {
1596 /* This just runs a program and remains */
1597 ++i;
1598 if (i < argc)
1599 {
1600 _tcscpy (commandline, _T("\""));
1601 _tcscat (commandline, argv[i]);
1602 _tcscat (commandline, _T("\""));
1603 while (++i < argc)
1604 {
1605 _tcscat (commandline, _T(" "));
1606 _tcscat (commandline, argv[i]);
1607 }
1608 ParseCommandLine(commandline);
1609 }
1610 }
1611 #ifdef INCLUDE_CMD_COLOR
1612 else if (!_tcsnicmp (argv[i], _T("/t:"), 3))
1613 {
1614 /* process /t (color) argument */
1615 wDefColor = (WORD)_tcstoul (&argv[i][3], NULL, 16);
1616 wColor = wDefColor;
1617 SetScreenColor (wColor, TRUE);
1618 }
1619 #endif
1620 }
1621 }
1622 else
1623 {
1624 /* Display a simple version string */
1625 ConOutPrintf(_T("ReactOS Operating System [Version %s-%s]\n"),
1626 _T(KERNEL_RELEASE_STR),
1627 _T(KERNEL_VERSION_BUILD_STR));
1628
1629 ConOutPuts (_T("(C) Copyright 1998-") _T(COPYRIGHT_YEAR) _T(" ReactOS Team.\n"));
1630 }
1631
1632 ExecuteAutoRunFile ();
1633
1634 #ifdef FEATURE_DIR_STACK
1635 /* initialize directory stack */
1636 InitDirectoryStack ();
1637 #endif
1638
1639
1640 #ifdef FEATURE_HISTORY
1641 /*initialize history*/
1642 InitHistory();
1643 #endif
1644
1645 /* Set COMSPEC environment variable */
1646 if (0 != GetModuleFileName (NULL, ModuleName, _MAX_PATH + 1))
1647 {
1648 ModuleName[_MAX_PATH] = _T('\0');
1649 SetEnvironmentVariable (_T("COMSPEC"), ModuleName);
1650 }
1651
1652 /* add ctrl break handler */
1653 AddBreakHandler ();
1654 }
1655
1656
1657 static VOID Cleanup (int argc, const TCHAR *argv[])
1658 {
1659 /* run cmdexit.bat */
1660 if (IsExistingFile (_T("cmdexit.bat")))
1661 {
1662 ConErrResPuts(STRING_CMD_ERROR5);
1663
1664 ParseCommandLine (_T("cmdexit.bat"));
1665 }
1666 else if (IsExistingFile (_T("\\cmdexit.bat")))
1667 {
1668 ConErrResPuts (STRING_CMD_ERROR5);
1669 ParseCommandLine (_T("\\cmdexit.bat"));
1670 }
1671
1672 #ifdef FEATURE_DIECTORY_STACK
1673 /* destroy directory stack */
1674 DestroyDirectoryStack ();
1675 #endif
1676
1677 #ifdef INCLUDE_CMD_CHDIR
1678 FreeLastPath ();
1679 #endif
1680
1681 #ifdef FEATURE_HISTORY
1682 CleanHistory();
1683 #endif
1684
1685
1686 /* remove ctrl break handler */
1687 RemoveBreakHandler ();
1688 SetConsoleMode( GetStdHandle( STD_INPUT_HANDLE ),
1689 ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT | ENABLE_ECHO_INPUT );
1690
1691 if (NtDllModule != NULL)
1692 {
1693 FreeLibrary(NtDllModule);
1694 }
1695 }
1696
1697 /*
1698 * main function
1699 */
1700 int cmd_main (int argc, const TCHAR *argv[])
1701 {
1702 TCHAR startPath[MAX_PATH];
1703 CONSOLE_SCREEN_BUFFER_INFO Info;
1704 INT nExitCode;
1705
1706 GetCurrentDirectory(MAX_PATH,startPath);
1707 _tchdir(startPath);
1708
1709 SetFileApisToOEM();
1710 InputCodePage= 0;
1711 OutputCodePage = 0;
1712
1713 hConsole = CreateFile(_T("CONOUT$"), GENERIC_READ|GENERIC_WRITE,
1714 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL,
1715 OPEN_EXISTING, 0, NULL);
1716 if (GetConsoleScreenBufferInfo(hConsole, &Info) == FALSE)
1717 {
1718 ConErrFormatMessage(GetLastError());
1719 return(1);
1720 }
1721 wColor = Info.wAttributes;
1722 wDefColor = wColor;
1723
1724 InputCodePage= GetConsoleCP();
1725 OutputCodePage = GetConsoleOutputCP();
1726 CMD_ModuleHandle = GetModuleHandle(NULL);
1727
1728 /* check switches on command-line */
1729 Initialize(argc, argv);
1730
1731 /* call prompt routine */
1732 nExitCode = ProcessInput(FALSE);
1733
1734 /* do the cleanup */
1735 Cleanup(argc, argv);
1736
1737 cmd_exit(nExitCode);
1738 return(nExitCode);
1739 }
1740
1741 /* EOF */