optimize 17218 by using memmove instead of memcopy and not using _tcsncmp. Suggested...
[reactos.git] / reactos / subsys / system / 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 <ekohl@abo.rhein-zeitung.de>)
88 * First ReactOS release.
89 * Extended length of commandline buffers to 512.
90 *
91 * 13-Dec-1998 (Eric Kohl <ekohl@abo.rhein-zeitung.de>)
92 * Added COMSPEC environment variable.
93 * Added "/t" support (color) on cmd command line.
94 *
95 * 07-Jan-1999 (Eric Kohl <ekohl@abo.rhein-zeitung.de>)
96 * Added help text ("cmd /?").
97 *
98 * 25-Jan-1999 (Eric Kohl <ekohl@abo.rhein-zeitung.de>)
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 <ekohl@abo.rhein-zeitung.de>)
105 * Replaced spawnl() by CreateProcess().
106 *
107 * 22-Oct-1999 (Eric Kohl <ekohl@abo.rhein-zeitung.de>)
108 * Added break handler.
109 *
110 * 15-Dec-1999 (Eric Kohl <ekohl@abo.rhein-zeitung.de>)
111 * Fixed current directory
112 *
113 * 28-Dec-1999 (Eric Kohl <ekohl@abo.rhein-zeitung.de>)
114 * Restore window title after program/batch execution
115 *
116 * 03-Feb-2001 (Eric Kohl <ekohl@rz-online.de>)
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 (Hartmut Birr)
126 * Removed MakeSureDirectoryPathExistsEx.
127 * Use the current directory if GetTempPath fails.
128 *
129 * 12-Jul-2004 (Jens Collin <jens.collin@lakhei.com>)
130 * Added ShellExecute call when all else fails to be able to "launch" any file.
131 *
132 * 02-Apr-2005 (Magnus Olsen <magnus@greatlord.com>)
133 * Remove all hardcode string to En.rc
134 *
135 * 06-May-2005 (Klemens Friedl <frik85@gmail.com>)
136 * Add 'help' command (list all commands plus description)
137 *
138 * 06-jul-2005 (Magnus Olsen <magnus@greatlord.com>)
139 * translate '%errorlevel%' to the internal value.
140 * Add proper memmory alloc ProcessInput, the error
141 * handling for memmory handling need to be improve
142 */
143
144 #include <precomp.h>
145 #include "resource.h"
146
147 #ifndef NT_SUCCESS
148 #define NT_SUCCESS(StatCode) ((NTSTATUS)(StatCode) >= 0)
149 #endif
150
151 typedef NTSTATUS (STDCALL *NtQueryInformationProcessProc)(HANDLE, PROCESSINFOCLASS,
152 PVOID, ULONG, PULONG);
153 typedef NTSTATUS (STDCALL *NtReadVirtualMemoryProc)(HANDLE, PVOID, PVOID, ULONG, PULONG);
154
155 BOOL bExit = FALSE; /* indicates EXIT was typed */
156 BOOL bCanExit = TRUE; /* indicates if this shell is exitable */
157 BOOL bCtrlBreak = FALSE; /* Ctrl-Break or Ctrl-C hit */
158 BOOL bIgnoreEcho = FALSE; /* Ignore 'newline' before 'cls' */
159 INT nErrorLevel = 0; /* Errorlevel of last launched external program */
160 BOOL bChildProcessRunning = FALSE;
161 DWORD dwChildProcessId = 0;
162 OSVERSIONINFO osvi;
163 HANDLE hIn;
164 HANDLE hOut;
165 HANDLE hConsole;
166 HANDLE CMD_ModuleHandle;
167 HMODULE NtDllModule;
168
169 static NtQueryInformationProcessProc NtQueryInformationProcessPtr = NULL;
170 static NtReadVirtualMemoryProc NtReadVirtualMemoryPtr = NULL;
171
172 #ifdef INCLUDE_CMD_COLOR
173 WORD wColor; /* current color */
174 WORD wDefColor; /* default color */
175 #endif
176
177 /*
178 * is character a delimeter when used on first word?
179 *
180 */
181
182 static BOOL IsDelimiter (TCHAR c)
183 {
184 return (c == _T('/') || c == _T('=') || c == _T('\0') || _istspace (c));
185 }
186
187 /*
188 * Is a process a console process?
189 */
190 static BOOL IsConsoleProcess(HANDLE Process)
191 {
192 NTSTATUS Status;
193 PROCESS_BASIC_INFORMATION Info;
194 PEB ProcessPeb;
195 ULONG BytesRead;
196
197 if (NULL == NtQueryInformationProcessPtr || NULL == NtReadVirtualMemoryPtr)
198 {
199 return TRUE;
200 }
201
202 Status = NtQueryInformationProcessPtr(Process, ProcessBasicInformation,
203 &Info, sizeof(PROCESS_BASIC_INFORMATION), NULL);
204 if (! NT_SUCCESS(Status))
205 {
206 #ifdef _DEBUG
207 DebugPrintf (_T("NtQueryInformationProcess failed with status %08x\n"), Status);
208 #endif
209 return TRUE;
210 }
211 Status = NtReadVirtualMemoryPtr(Process, Info.PebBaseAddress, &ProcessPeb,
212 sizeof(PEB), &BytesRead);
213 if (! NT_SUCCESS(Status) || sizeof(PEB) != BytesRead)
214 {
215 #ifdef _DEBUG
216 DebugPrintf (_T("Couldn't read virt mem status %08x bytes read %lu\n"), Status, BytesRead);
217 #endif
218 return TRUE;
219 }
220
221 return IMAGE_SUBSYSTEM_WINDOWS_CUI == ProcessPeb.ImageSubSystem;
222 }
223
224
225
226 #ifdef _UNICODE
227 #define SHELLEXECUTETEXT "ShellExecuteW"
228 #else
229 #define SHELLEXECUTETEXT "ShellExecuteA"
230 #endif
231
232 typedef HINSTANCE (WINAPI *MYEX)(
233 HWND hwnd,
234 LPCTSTR lpOperation,
235 LPCTSTR lpFile,
236 LPCTSTR lpParameters,
237 LPCTSTR lpDirectory,
238 INT nShowCmd
239 );
240
241
242
243 static BOOL RunFile(LPTSTR filename)
244 {
245 HMODULE hShell32;
246 MYEX hShExt;
247 HINSTANCE ret;
248
249 #ifdef _DEBUG
250 DebugPrintf (_T("RunFile(%s)\n"), filename);
251 #endif
252 hShell32 = LoadLibrary(_T("SHELL32.DLL"));
253 if (!hShell32)
254 {
255 #ifdef _DEBUG
256 DebugPrintf (_T("RunFile: couldn't load SHELL32.DLL!\n"));
257 #endif
258 return FALSE;
259 }
260
261 hShExt = (MYEX)(FARPROC)GetProcAddress(hShell32, SHELLEXECUTETEXT);
262 if (!hShExt)
263 {
264 #ifdef _DEBUG
265 DebugPrintf (_T("RunFile: couldn't find ShellExecuteA/W in SHELL32.DLL!\n"));
266 #endif
267 FreeLibrary(hShell32);
268 return FALSE;
269 }
270
271 #ifdef _DEBUG
272 DebugPrintf (_T("RunFile: ShellExecuteA/W is at %x\n"), hShExt);
273 #endif
274
275 ret = (hShExt)(NULL, _T("open"), filename, NULL, NULL, SW_SHOWNORMAL);
276
277 #ifdef _DEBUG
278 DebugPrintf (_T("RunFile: ShellExecuteA/W returned %d\n"), (DWORD)ret);
279 #endif
280
281 FreeLibrary(hShell32);
282 return (((DWORD)ret) > 32);
283 }
284
285
286
287 /*
288 * This command (in first) was not found in the command table
289 *
290 * Full - whole command line
291 * First - first word on command line
292 * Rest - rest of command line
293 */
294
295 static VOID
296 Execute (LPTSTR Full, LPTSTR First, LPTSTR Rest)
297 {
298 TCHAR szFullName[MAX_PATH];
299 TCHAR first[CMDLINE_LENGTH];
300 TCHAR rest[CMDLINE_LENGTH];
301 TCHAR full[CMDLINE_LENGTH];
302 #ifndef __REACTOS__
303 TCHAR szWindowTitle[MAX_PATH];
304 #endif
305 DWORD dwExitCode = 0;
306
307 #ifdef _DEBUG
308 DebugPrintf (_T("Execute: \'%s\' \'%s\'\n"), first, rest);
309 #endif
310
311 /* Though it was already parsed once, we have a different set of rules
312 for parsing before we pass to CreateProccess */
313 if(!_tcschr(Full,_T('\"')))
314 {
315 _tcscpy(first,First);
316 _tcscpy(rest,Rest);
317 _tcscpy(full,Full);
318 }
319 else
320 {
321 INT i = 0;
322 BOOL bInside = FALSE;
323 rest[0] = _T('\0');
324 full[0] = _T('\0');
325 first[0] = _T('\0');
326 _tcscpy(first,Full);
327 /* find the end of the command and start of the args */
328 for(i = 0; i < _tcslen(first); i++)
329 {
330 if(!_tcsncmp(&first[i], _T("\""), 1))
331 bInside = !bInside;
332 if(!_tcsncmp(&first[i], _T(" "), 1) && !bInside)
333 {
334 _tcscpy(rest,&first[i]);
335 first[i] = _T('\0');
336 break;
337 }
338
339 }
340 i = 0;
341 /* remove any slashes */
342 while(i < _tcslen(first))
343 {
344 if(first[i] == _T('\"'))
345 memmove(&first[i],&first[i + 1], _tcslen(&first[i]) * sizeof(TCHAR));
346 else
347 i++;
348 }
349 /* Drop quotes around it just in case there is a space */
350 _tcscpy(full,_T("\""));
351 _tcscat(full,first);
352 _tcscat(full,_T("\" "));
353 _tcscat(full,rest);
354 }
355
356 /* check for a drive change */
357 if ((_istalpha (first[0])) && (!_tcscmp (first + 1, _T(":"))))
358 {
359 BOOL working = TRUE;
360 if (!SetCurrentDirectory(first))
361 /* Guess they changed disc or something, handle that gracefully and get to root */
362 {
363 TCHAR str[4];
364 str[0]=first[0];
365 str[1]=_T(':');
366 str[2]=_T('\\');
367 str[3]=0;
368 working = SetCurrentDirectory(str);
369 }
370
371 if (!working) ConErrResPuts (STRING_FREE_ERROR1);
372
373 return;
374 }
375
376 /* get the PATH environment variable and parse it */
377 /* search the PATH environment variable for the binary */
378 if (!SearchForExecutable (first, szFullName))
379 {
380 error_bad_command ();
381 return;
382 }
383
384 #ifndef __REACTOS__
385 GetConsoleTitle (szWindowTitle, MAX_PATH);
386 #endif
387
388 /* check if this is a .BAT or .CMD file */
389 if (!_tcsicmp (_tcsrchr (szFullName, _T('.')), _T(".bat")) ||
390 !_tcsicmp (_tcsrchr (szFullName, _T('.')), _T(".cmd")))
391 {
392 #ifdef _DEBUG
393 DebugPrintf (_T("[BATCH: %s %s]\n"), szFullName, rest);
394 #endif
395 Batch (szFullName, first, rest);
396 }
397 else
398 {
399 /* exec the program */
400 PROCESS_INFORMATION prci;
401 STARTUPINFO stui;
402
403 #ifdef _DEBUG
404 DebugPrintf (_T("[EXEC: %s %s]\n"), full, rest);
405 #endif
406 /* build command line for CreateProcess() */
407
408 /* fill startup info */
409 memset (&stui, 0, sizeof (STARTUPINFO));
410 stui.cb = sizeof (STARTUPINFO);
411 stui.dwFlags = STARTF_USESHOWWINDOW;
412 stui.wShowWindow = SW_SHOWDEFAULT;
413
414 // return console to standard mode
415 SetConsoleMode (GetStdHandle(STD_INPUT_HANDLE),
416 ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT | ENABLE_ECHO_INPUT );
417
418 if (CreateProcess (szFullName,
419 full,
420 NULL,
421 NULL,
422 TRUE,
423 CREATE_NEW_PROCESS_GROUP,
424 NULL,
425 NULL,
426 &stui,
427 &prci))
428 {
429 if (IsConsoleProcess(prci.hProcess))
430 {
431 /* FIXME: Protect this with critical section */
432 bChildProcessRunning = TRUE;
433 dwChildProcessId = prci.dwProcessId;
434
435 WaitForSingleObject (prci.hProcess, INFINITE);
436
437 /* FIXME: Protect this with critical section */
438 bChildProcessRunning = FALSE;
439
440 GetExitCodeProcess (prci.hProcess, &dwExitCode);
441 nErrorLevel = (INT)dwExitCode;
442 }
443 CloseHandle (prci.hThread);
444 CloseHandle (prci.hProcess);
445 }
446 else
447 {
448 #ifdef _DEBUG
449 DebugPrintf (_T("[ShellExecute: %s]\n"), full);
450 #endif
451 // See if we can run this with ShellExecute() ie myfile.xls
452 if (!RunFile(full))
453 {
454 #ifdef _DEBUG
455 DebugPrintf (_T("[ShellExecute failed!: %s]\n"), full);
456 #endif
457 error_bad_command ();
458 }
459 }
460 // restore console mode
461 SetConsoleMode( GetStdHandle( STD_INPUT_HANDLE ),
462 ENABLE_PROCESSED_INPUT );
463 }
464
465 /* Get code page if it has been change */
466 InputCodePage= GetConsoleCP();
467 OutputCodePage = GetConsoleOutputCP();
468 #ifndef __REACTOS__
469 SetConsoleTitle (szWindowTitle);
470 #endif
471 }
472
473
474 /*
475 * look through the internal commands and determine whether or not this
476 * command is one of them. If it is, call the command. If not, call
477 * execute to run it as an external program.
478 *
479 * line - the command line of the program to run
480 *
481 */
482
483 static VOID
484 DoCommand (LPTSTR line)
485 {
486 TCHAR com[CMDLINE_LENGTH]; /* the first word in the command */
487 LPTSTR cp = com;
488 LPTSTR cstart;
489 LPTSTR rest; /* pointer to the rest of the command line */
490 INT cl;
491 LPCOMMAND cmdptr;
492
493 #ifdef _DEBUG
494 DebugPrintf (_T("DoCommand: (\'%s\')\n"), line);
495 #endif /* DEBUG */
496
497 /* Skip over initial white space */
498 while (_istspace (*line))
499 line++;
500 rest = line;
501
502 cstart = rest;
503
504 /* Anything to do ? */
505 if (*rest)
506 {
507 if (*rest == _T('"'))
508 {
509 /* treat quoted words specially */
510
511 rest++;
512
513 while(*rest != _T('\0') && *rest != _T('"'))
514 *cp++ = _totlower (*rest++);
515 if (*rest == _T('"'))
516 rest++;
517 }
518 else
519 {
520 while (!IsDelimiter (*rest))
521 *cp++ = _totlower (*rest++);
522 }
523
524
525 /* Terminate first word */
526 *cp = _T('\0');
527
528 /* commands are limited to MAX_PATH */
529 if(_tcslen(com) > MAX_PATH)
530 {
531 error_bad_command();
532 return;
533 }
534
535 /* Skip over whitespace to rest of line */
536 while (_istspace (*rest))
537 rest++;
538
539 /* Scan internal command table */
540 for (cmdptr = cmds;; cmdptr++)
541 {
542 /* If end of table execute ext cmd */
543 if (cmdptr->name == NULL)
544 {
545 Execute (line, com, rest);
546 break;
547 }
548
549 if (!_tcscmp (com, cmdptr->name))
550 {
551 cmdptr->func (com, rest);
552 break;
553 }
554
555 /* The following code handles the case of commands like CD which
556 * are recognised even when the command name and parameter are
557 * not space separated.
558 *
559 * e.g dir..
560 * cd\freda
561 */
562
563 /* Get length of command name */
564 cl = _tcslen (cmdptr->name);
565
566 if ((cmdptr->flags & CMD_SPECIAL) &&
567 (!_tcsncmp (cmdptr->name, com, cl)) &&
568 (_tcschr (_T("\\.-"), *(com + cl))))
569 {
570 /* OK its one of the specials...*/
571
572 /* Terminate first word properly */
573 com[cl] = _T('\0');
574
575 /* Call with new rest */
576 cmdptr->func (com, cstart + cl);
577 break;
578 }
579 }
580 }
581 }
582
583
584 /*
585 * process the command line and execute the appropriate functions
586 * full input/output redirection and piping are supported
587 */
588
589 VOID ParseCommandLine (LPTSTR cmd)
590 {
591 TCHAR szMsg[RC_STRING_MAX_SIZE];
592 TCHAR cmdline[CMDLINE_LENGTH];
593 LPTSTR s;
594 #ifdef FEATURE_REDIRECTION
595 TCHAR in[CMDLINE_LENGTH] = _T("");
596 TCHAR out[CMDLINE_LENGTH] = _T("");
597 TCHAR err[CMDLINE_LENGTH] = _T("");
598 TCHAR szTempPath[MAX_PATH] = _T(".\\");
599 TCHAR szFileName[2][MAX_PATH] = {_T(""), _T("")};
600 HANDLE hFile[2] = {INVALID_HANDLE_VALUE, INVALID_HANDLE_VALUE};
601 LPTSTR t = NULL;
602 INT num = 0;
603 INT nRedirFlags = 0;
604 INT Length;
605 UINT Attributes;
606 BOOL bNewBatch = TRUE;
607 HANDLE hOldConIn;
608 HANDLE hOldConOut;
609 HANDLE hOldConErr;
610 #endif /* FEATURE_REDIRECTION */
611
612 _tcscpy (cmdline, cmd);
613 s = &cmdline[0];
614
615 #ifdef _DEBUG
616 DebugPrintf (_T("ParseCommandLine: (\'%s\')\n"), s);
617 #endif /* DEBUG */
618
619 #ifdef FEATURE_ALIASES
620 /* expand all aliases */
621 ExpandAlias (s, CMDLINE_LENGTH);
622 #endif /* FEATURE_ALIAS */
623
624 #ifdef FEATURE_REDIRECTION
625 /* find the temp path to store temporary files */
626 Length = GetTempPath (MAX_PATH, szTempPath);
627 if (Length > 0 && Length < MAX_PATH)
628 {
629 Attributes = GetFileAttributes(szTempPath);
630 if (Attributes == 0xffffffff ||
631 !(Attributes & FILE_ATTRIBUTE_DIRECTORY))
632 {
633 Length = 0;
634 }
635 }
636 if (Length == 0 || Length >= MAX_PATH)
637 {
638 _tcscpy(szTempPath, _T(".\\"));
639 }
640 if (szTempPath[_tcslen (szTempPath) - 1] != _T('\\'))
641 _tcscat (szTempPath, _T("\\"));
642
643 /* get the redirections from the command line */
644 num = GetRedirection (s, in, out, err, &nRedirFlags);
645
646 /* more efficient, but do we really need to do this? */
647 for (t = in; _istspace (*t); t++)
648 ;
649 _tcscpy (in, t);
650
651 for (t = out; _istspace (*t); t++)
652 ;
653 _tcscpy (out, t);
654
655 for (t = err; _istspace (*t); t++)
656 ;
657 _tcscpy (err, t);
658
659 if(bc && !_tcslen (in) && _tcslen (bc->In))
660 _tcscpy(in, bc->In);
661 if(bc && !out[0] && _tcslen(bc->Out))
662 {
663 nRedirFlags |= OUTPUT_APPEND;
664 _tcscpy(out, bc->Out);
665 }
666 if(bc && !_tcslen (err) && _tcslen (bc->Err))
667 {
668 nRedirFlags |= ERROR_APPEND;
669 _tcscpy(err, bc->Err);
670 }
671
672
673 /* Set up the initial conditions ... */
674 /* preserve STDIN, STDOUT and STDERR handles */
675 hOldConIn = GetStdHandle (STD_INPUT_HANDLE);
676 hOldConOut = GetStdHandle (STD_OUTPUT_HANDLE);
677 hOldConErr = GetStdHandle (STD_ERROR_HANDLE);
678
679 /* redirect STDIN */
680 if (in[0])
681 {
682 HANDLE hFile;
683 SECURITY_ATTRIBUTES sa = {sizeof(SECURITY_ATTRIBUTES), NULL, TRUE};
684
685 /* we need make sure the LastError msg is zero before calling CreateFile */
686 SetLastError(0);
687
688 /* Set up pipe for the standard input handler */
689 hFile = CreateFile (in, GENERIC_READ, FILE_SHARE_READ, &sa, OPEN_EXISTING,
690 FILE_ATTRIBUTE_NORMAL, NULL);
691 if (hFile == INVALID_HANDLE_VALUE)
692 {
693 LoadString(CMD_ModuleHandle, STRING_CMD_ERROR1, szMsg, RC_STRING_MAX_SIZE);
694 ConErrPrintf(szMsg, in);
695 return;
696 }
697
698 if (!SetStdHandle (STD_INPUT_HANDLE, hFile))
699 {
700 LoadString(CMD_ModuleHandle, STRING_CMD_ERROR1, szMsg, RC_STRING_MAX_SIZE);
701 ConErrPrintf(szMsg, in);
702 return;
703 }
704 #ifdef _DEBUG
705 DebugPrintf (_T("Input redirected from: %s\n"), in);
706 #endif
707 }
708
709 /* Now do all but the last pipe command */
710 *szFileName[0] = _T('\0');
711 hFile[0] = INVALID_HANDLE_VALUE;
712
713 while (num-- > 1)
714 {
715 SECURITY_ATTRIBUTES sa = {sizeof(SECURITY_ATTRIBUTES), NULL, TRUE};
716
717 /* Create unique temporary file name */
718 GetTempFileName (szTempPath, _T("CMD"), 0, szFileName[1]);
719
720 /* we need make sure the LastError msg is zero before calling CreateFile */
721 SetLastError(0);
722
723 /* Set current stdout to temporary file */
724 hFile[1] = CreateFile (szFileName[1], GENERIC_WRITE, 0, &sa,
725 TRUNCATE_EXISTING, FILE_ATTRIBUTE_TEMPORARY, NULL);
726
727 if (hFile[1] == INVALID_HANDLE_VALUE)
728 {
729 LoadString(CMD_ModuleHandle, STRING_CMD_ERROR2, szMsg, RC_STRING_MAX_SIZE);
730 ConErrPrintf(szMsg);
731 return;
732 }
733
734 SetStdHandle (STD_OUTPUT_HANDLE, hFile[1]);
735
736 DoCommand (s);
737
738 /* close stdout file */
739 SetStdHandle (STD_OUTPUT_HANDLE, hOldConOut);
740 if ((hFile[1] != INVALID_HANDLE_VALUE) && (hFile[1] != hOldConOut))
741 {
742 CloseHandle (hFile[1]);
743 hFile[1] = INVALID_HANDLE_VALUE;
744 }
745
746 /* close old stdin file */
747 SetStdHandle (STD_INPUT_HANDLE, hOldConIn);
748 if ((hFile[0] != INVALID_HANDLE_VALUE) && (hFile[0] != hOldConIn))
749 {
750 /* delete old stdin file, if it is a real file */
751 CloseHandle (hFile[0]);
752 hFile[0] = INVALID_HANDLE_VALUE;
753 DeleteFile (szFileName[0]);
754 *szFileName[0] = _T('\0');
755 }
756
757 /* copy stdout file name to stdin file name */
758 _tcscpy (szFileName[0], szFileName[1]);
759 *szFileName[1] = _T('\0');
760
761 /* we need make sure the LastError msg is zero before calling CreateFile */
762 SetLastError(0);
763
764 /* open new stdin file */
765 hFile[0] = CreateFile (szFileName[0], GENERIC_READ, 0, &sa,
766 OPEN_EXISTING, FILE_ATTRIBUTE_TEMPORARY, NULL);
767 SetStdHandle (STD_INPUT_HANDLE, hFile[0]);
768
769 s = s + _tcslen (s) + 1;
770 }
771
772 /* Now set up the end conditions... */
773 /* redirect STDOUT */
774 if (out[0])
775 {
776 /* Final output to here */
777 HANDLE hFile;
778 SECURITY_ATTRIBUTES sa = {sizeof(SECURITY_ATTRIBUTES), NULL, TRUE};
779
780 /* we need make sure the LastError msg is zero before calling CreateFile */
781 SetLastError(0);
782
783 hFile = CreateFile (out, GENERIC_WRITE, FILE_SHARE_WRITE | FILE_SHARE_READ | FILE_SHARE_DELETE, &sa,
784 (nRedirFlags & OUTPUT_APPEND) ? OPEN_ALWAYS : CREATE_ALWAYS,
785 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, NULL);
786
787 if (hFile == INVALID_HANDLE_VALUE)
788 {
789 INT size = _tcslen(out)-1;
790
791 if (out[size] != _T(':'))
792 {
793 LoadString(CMD_ModuleHandle, STRING_CMD_ERROR3, szMsg, RC_STRING_MAX_SIZE);
794 ConErrPrintf(szMsg, out);
795 return;
796 }
797
798 out[size]=_T('\0');
799 hFile = CreateFile (out, GENERIC_WRITE, FILE_SHARE_WRITE | FILE_SHARE_READ | FILE_SHARE_DELETE, &sa,
800 (nRedirFlags & OUTPUT_APPEND) ? OPEN_ALWAYS : CREATE_ALWAYS,
801 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, NULL);
802
803 if (hFile == INVALID_HANDLE_VALUE)
804 {
805 LoadString(CMD_ModuleHandle, STRING_CMD_ERROR3, szMsg, RC_STRING_MAX_SIZE);
806 ConErrPrintf(szMsg, out);
807 return;
808 }
809
810 }
811
812 if (!SetStdHandle (STD_OUTPUT_HANDLE, hFile))
813 {
814 LoadString(CMD_ModuleHandle, STRING_CMD_ERROR3, szMsg, RC_STRING_MAX_SIZE);
815 ConErrPrintf(szMsg, out);
816 return;
817 }
818
819 if (nRedirFlags & OUTPUT_APPEND)
820 {
821 LONG lHighPos = 0;
822
823 if (GetFileType (hFile) == FILE_TYPE_DISK)
824 SetFilePointer (hFile, 0, &lHighPos, FILE_END);
825 }
826 #ifdef _DEBUG
827 DebugPrintf (_T("Output redirected to: %s\n"), out);
828 #endif
829 }
830 else if (hOldConOut != INVALID_HANDLE_VALUE)
831 {
832 /* Restore original stdout */
833 HANDLE hOut = GetStdHandle (STD_OUTPUT_HANDLE);
834 SetStdHandle (STD_OUTPUT_HANDLE, hOldConOut);
835 if (hOldConOut != hOut)
836 CloseHandle (hOut);
837 hOldConOut = INVALID_HANDLE_VALUE;
838 }
839
840 /* redirect STDERR */
841 if (err[0])
842 {
843 /* Final output to here */
844 HANDLE hFile;
845 SECURITY_ATTRIBUTES sa = {sizeof(SECURITY_ATTRIBUTES), NULL, TRUE};
846
847 if (!_tcscmp (err, out))
848 {
849 #ifdef _DEBUG
850 DebugPrintf (_T("Stdout and stderr will use the same file!!\n"));
851 #endif
852 DuplicateHandle (GetCurrentProcess (),
853 GetStdHandle (STD_OUTPUT_HANDLE),
854 GetCurrentProcess (),
855 &hFile, 0, TRUE, DUPLICATE_SAME_ACCESS);
856 }
857 else
858 {
859 hFile = CreateFile (err,
860 GENERIC_WRITE,
861 FILE_SHARE_WRITE | FILE_SHARE_READ | FILE_SHARE_DELETE,
862 &sa,
863 (nRedirFlags & ERROR_APPEND) ? OPEN_ALWAYS : CREATE_ALWAYS,
864 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH,
865 NULL);
866 if (hFile == INVALID_HANDLE_VALUE)
867 {
868 LoadString(CMD_ModuleHandle, STRING_CMD_ERROR3, szMsg, RC_STRING_MAX_SIZE);
869 ConErrPrintf(szMsg, err);
870 return;
871 }
872 }
873
874 if (!SetStdHandle (STD_ERROR_HANDLE, hFile))
875 {
876 LoadString(CMD_ModuleHandle, STRING_CMD_ERROR3, szMsg, RC_STRING_MAX_SIZE);
877 ConErrPrintf(szMsg, err);
878 return;
879 }
880
881 if (nRedirFlags & ERROR_APPEND)
882 {
883 LONG lHighPos = 0;
884
885 if (GetFileType (hFile) == FILE_TYPE_DISK)
886 SetFilePointer (hFile, 0, &lHighPos, FILE_END);
887 }
888 #ifdef _DEBUG
889 DebugPrintf (_T("Error redirected to: %s\n"), err);
890 #endif
891 }
892 else if (hOldConErr != INVALID_HANDLE_VALUE)
893 {
894 /* Restore original stderr */
895 HANDLE hErr = GetStdHandle (STD_ERROR_HANDLE);
896 SetStdHandle (STD_ERROR_HANDLE, hOldConErr);
897 if (hOldConErr != hErr)
898 CloseHandle (hErr);
899 hOldConErr = INVALID_HANDLE_VALUE;
900 }
901
902 if(bc)
903 bNewBatch = FALSE;
904 #endif
905
906 /* process final command */
907 DoCommand (s);
908
909 #ifdef FEATURE_REDIRECTION
910 if(bNewBatch && bc)
911 AddBatchRedirection(in, out, err);
912 /* close old stdin file */
913 #if 0 /* buggy implementation */
914 SetStdHandle (STD_INPUT_HANDLE, hOldConIn);
915 if ((hFile[0] != INVALID_HANDLE_VALUE) &&
916 (hFile[0] != hOldConIn))
917 {
918 /* delete old stdin file, if it is a real file */
919 CloseHandle (hFile[0]);
920 hFile[0] = INVALID_HANDLE_VALUE;
921 DeleteFile (szFileName[0]);
922 *szFileName[0] = _T('\0');
923 }
924
925 /* Restore original STDIN */
926 if (hOldConIn != INVALID_HANDLE_VALUE)
927 {
928 HANDLE hIn = GetStdHandle (STD_INPUT_HANDLE);
929 SetStdHandle (STD_INPUT_HANDLE, hOldConIn);
930 if (hOldConIn != hIn)
931 CloseHandle (hIn);
932 hOldConIn = INVALID_HANDLE_VALUE;
933 }
934 else
935 {
936 #ifdef _DEBUG
937 DebugPrintf (_T("Can't restore STDIN! Is invalid!!\n"), out);
938 #endif
939 }
940 #endif /* buggy implementation */
941
942
943 if (hOldConIn != INVALID_HANDLE_VALUE)
944 {
945 HANDLE hIn = GetStdHandle (STD_INPUT_HANDLE);
946 SetStdHandle (STD_INPUT_HANDLE, hOldConIn);
947 if (hIn == INVALID_HANDLE_VALUE)
948 {
949 #ifdef _DEBUG
950 DebugPrintf (_T("Previous STDIN is invalid!!\n"));
951 #endif
952 }
953 else
954 {
955 if (GetFileType (hIn) == FILE_TYPE_DISK)
956 {
957 if (hFile[0] == hIn)
958 {
959 CloseHandle (hFile[0]);
960 hFile[0] = INVALID_HANDLE_VALUE;
961 DeleteFile (szFileName[0]);
962 *szFileName[0] = _T('\0');
963 }
964 else
965 {
966 #ifdef _DEBUG
967 DebugPrintf (_T("hFile[0] and hIn dont match!!!\n"));
968 #endif
969 }
970 }
971 }
972 }
973
974
975 /* Restore original STDOUT */
976 if (hOldConOut != INVALID_HANDLE_VALUE)
977 {
978 HANDLE hOut = GetStdHandle (STD_OUTPUT_HANDLE);
979 SetStdHandle (STD_OUTPUT_HANDLE, hOldConOut);
980 if (hOldConOut != hOut)
981 CloseHandle (hOut);
982 hOldConOut = INVALID_HANDLE_VALUE;
983 }
984
985 /* Restore original STDERR */
986 if (hOldConErr != INVALID_HANDLE_VALUE)
987 {
988 HANDLE hErr = GetStdHandle (STD_ERROR_HANDLE);
989 SetStdHandle (STD_ERROR_HANDLE, hOldConErr);
990 if (hOldConErr != hErr)
991 CloseHandle (hErr);
992 hOldConErr = INVALID_HANDLE_VALUE;
993 }
994 #endif /* FEATURE_REDIRECTION */
995 }
996
997
998 /*
999 * do the prompt/input/process loop
1000 *
1001 */
1002
1003 static INT
1004 ProcessInput (BOOL bFlag)
1005 {
1006 TCHAR commandline[CMDLINE_LENGTH];
1007 TCHAR readline[CMDLINE_LENGTH];
1008 LPTSTR tp = NULL;
1009 LPTSTR ip;
1010 LPTSTR cp;
1011 BOOL bEchoThisLine;
1012
1013
1014 do
1015 {
1016 /* if no batch input then... */
1017 if (!(ip = ReadBatchLine (&bEchoThisLine)))
1018 {
1019 if (bFlag)
1020 return 0;
1021
1022 ReadCommand (readline, CMDLINE_LENGTH);
1023 ip = readline;
1024 bEchoThisLine = FALSE;
1025 }
1026
1027 cp = commandline;
1028 while (*ip)
1029 {
1030 if (*ip == _T('%'))
1031 {
1032 switch (*++ip)
1033 {
1034 case _T('%'):
1035 *cp++ = *ip++;
1036 break;
1037
1038 case _T('0'):
1039 case _T('1'):
1040 case _T('2'):
1041 case _T('3'):
1042 case _T('4'):
1043 case _T('5'):
1044 case _T('6'):
1045 case _T('7'):
1046 case _T('8'):
1047 case _T('9'):
1048 if ((tp = FindArg (*ip - _T('0'))))
1049 {
1050 cp = _stpcpy (cp, tp);
1051 ip++;
1052 }
1053 else
1054 *cp++ = _T('%');
1055 break;
1056
1057 case _T('?'):
1058 cp += _stprintf (cp, _T("%u"), nErrorLevel);
1059 ip++;
1060 break;
1061
1062 default:
1063 tp = _tcschr(ip, _T('%'));
1064 if ((tp != NULL) &&
1065 (tp <= _tcschr(ip, _T(' ')) - 1))
1066 {
1067 INT size = 512;
1068 TCHAR *evar;
1069 *tp = _T('\0');
1070
1071 /* FIXME: Correct error handling when it can not alloc memmory */
1072
1073 /* %CD% */
1074 if (_tcsicmp(ip,_T("cd")) ==0)
1075 {
1076 TCHAR szPath[MAX_PATH];
1077 GetCurrentDirectory (MAX_PATH, szPath);
1078 cp = _stpcpy (cp, szPath);
1079 }
1080
1081 /* %TIME% */
1082 else if (_tcsicmp(ip,_T("time")) ==0)
1083 {
1084 TCHAR szTime[40];
1085 SYSTEMTIME t;
1086 GetSystemTime(&t);
1087
1088 _sntprintf(szTime ,40,_T("%02d%c%02d%c%02d%c%02d"), t.wHour, cTimeSeparator,t.wMinute , cTimeSeparator,t.wSecond , cDecimalSeparator, t.wMilliseconds );
1089 cp = _stpcpy (cp, szTime);
1090 }
1091
1092 /* %DATE% */
1093 else if (_tcsicmp(ip,_T("date")) ==0)
1094 {
1095 TCHAR szDate[40];
1096
1097 GetDateFormat(LOCALE_USER_DEFAULT, 0, NULL, _T("ddd"), szDate, sizeof (szDate));
1098 cp = _stpcpy (cp, szDate);
1099 cp = _stpcpy (cp, _T(" "));
1100 GetDateFormat(LOCALE_USER_DEFAULT, DATE_SHORTDATE, NULL, NULL, szDate, sizeof (szDate));
1101 cp = _stpcpy (cp, szDate);
1102 }
1103
1104 /* %RANDOM% */
1105 else if (_tcsicmp(ip,_T("random")) ==0)
1106 {
1107 TCHAR szRand[40];
1108 /* Get random number */
1109 _itot(rand(),szRand,10);
1110 cp = _stpcpy (cp, szRand);
1111 }
1112
1113 /* %CMDCMDLINE% */
1114 else if (_tcsicmp(ip,_T("cmdcmdline")) ==0)
1115 {
1116 TCHAR *pargv;
1117 /* Get random number */
1118 pargv = GetCommandLine();
1119 cp = _stpcpy (cp, pargv);
1120 }
1121
1122 /* %CMDEXTVERSION% */
1123 else if (_tcsicmp(ip,_T("cmdextversion")) ==0)
1124 {
1125 TCHAR szVER[40];
1126 /* Set version number to 2 */
1127 _itot(2,szVER,10);
1128 cp = _stpcpy (cp, szVER);
1129 }
1130
1131 /* %ERRORLEVEL% */
1132 else if (_tcsicmp(ip,_T("errorlevel")) ==0)
1133 {
1134 evar = malloc ( size * sizeof(TCHAR));
1135 if (evar==NULL)
1136 return 1;
1137
1138 memset(evar,0,512 * sizeof(TCHAR));
1139 _itot(nErrorLevel,evar,10);
1140 cp = _stpcpy (cp, evar);
1141
1142 free(evar);
1143 }
1144 else
1145 {
1146 evar = malloc ( 512 * sizeof(TCHAR));
1147 if (evar==NULL)
1148 return 1;
1149
1150 size = GetEnvironmentVariable (ip, evar, 512);
1151 if (size > 512)
1152 {
1153 evar = realloc(evar,size * sizeof(TCHAR) );
1154 if (evar==NULL)
1155 {
1156 return 1;
1157 }
1158 size = GetEnvironmentVariable (ip, evar, size);
1159 }
1160
1161 if (size)
1162 {
1163 cp = _stpcpy (cp, evar);
1164 }
1165
1166 free(evar);
1167 }
1168
1169 ip = tp + 1;
1170
1171 }
1172 else
1173 {
1174 *cp++ = _T('%');
1175 }
1176
1177 break;
1178 }
1179 continue;
1180 }
1181
1182
1183
1184
1185 if (_istcntrl (*ip))
1186 *ip = _T(' ');
1187 *cp++ = *ip++;
1188 }
1189
1190 *cp = _T('\0');
1191
1192 /* strip trailing spaces */
1193 while ((--cp >= commandline) && _istspace (*cp));
1194
1195 *(cp + 1) = _T('\0');
1196
1197 /* JPP 19980807 */
1198 /* Echo batch file line */
1199 if (bEchoThisLine)
1200 {
1201 PrintPrompt ();
1202 ConOutPuts (commandline);
1203 }
1204
1205 if (*commandline)
1206 {
1207 ParseCommandLine (commandline);
1208 if (bEcho && !bIgnoreEcho)
1209 ConOutChar ('\n');
1210 bIgnoreEcho = FALSE;
1211 }
1212 }
1213 while (!bCanExit || !bExit);
1214
1215 return 0;
1216 }
1217
1218
1219 /*
1220 * control-break handler.
1221 */
1222 BOOL WINAPI BreakHandler (DWORD dwCtrlType)
1223 {
1224
1225 if ((dwCtrlType != CTRL_C_EVENT) &&
1226 (dwCtrlType != CTRL_BREAK_EVENT))
1227 return FALSE;
1228
1229 if (bChildProcessRunning == TRUE)
1230 {
1231 GenerateConsoleCtrlEvent (CTRL_C_EVENT,
1232 dwChildProcessId);
1233 return TRUE;
1234 }
1235
1236 /* FIXME: Handle batch files */
1237
1238 /* FIXME: Print "^C" */
1239
1240
1241 return TRUE;
1242 }
1243
1244
1245 VOID AddBreakHandler (VOID)
1246 {
1247 SetConsoleCtrlHandler ((PHANDLER_ROUTINE)BreakHandler, TRUE);
1248 }
1249
1250
1251 VOID RemoveBreakHandler (VOID)
1252 {
1253 SetConsoleCtrlHandler ((PHANDLER_ROUTINE)BreakHandler, FALSE);
1254 }
1255
1256
1257 /*
1258 * show commands and options that are available.
1259 *
1260 */
1261 #if 0
1262 static VOID
1263 ShowCommands (VOID)
1264 {
1265 /* print command list */
1266 ConOutResPuts(STRING_CMD_HELP1);
1267 PrintCommandList();
1268
1269 /* print feature list */
1270 ConOutResPuts(STRING_CMD_HELP2);
1271
1272 #ifdef FEATURE_ALIASES
1273 ConOutResPuts(STRING_CMD_HELP3);
1274 #endif
1275 #ifdef FEATURE_HISTORY
1276 ConOutResPuts(STRING_CMD_HELP4);
1277 #endif
1278 #ifdef FEATURE_UNIX_FILENAME_COMPLETION
1279 ConOutResPuts(STRING_CMD_HELP5);
1280 #endif
1281 #ifdef FEATURE_DIRECTORY_STACK
1282 ConOutResPuts(STRING_CMD_HELP6);
1283 #endif
1284 #ifdef FEATURE_REDIRECTION
1285 ConOutResPuts(STRING_CMD_HELP7);
1286 #endif
1287 ConOutChar(_T('\n'));
1288 }
1289 #endif
1290
1291 /*
1292 * set up global initializations and process parameters
1293 *
1294 * argc - number of parameters to command.com
1295 * argv - command-line parameters
1296 *
1297 */
1298 static VOID
1299 Initialize (int argc, TCHAR* argv[])
1300 {
1301 TCHAR commandline[CMDLINE_LENGTH];
1302 TCHAR ModuleName[_MAX_PATH + 1];
1303 INT i;
1304
1305 //INT len;
1306 //TCHAR *ptr, *cmdLine;
1307
1308 /* get version information */
1309 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1310 GetVersionEx (&osvi);
1311
1312 /* Some people like to run ReactOS cmd.exe on Win98, it helps in the
1313 build process. So don't link implicitly against ntdll.dll, load it
1314 dynamically instead */
1315
1316 if (osvi.dwPlatformId == VER_PLATFORM_WIN32_NT)
1317 {
1318 /* ntdll is always present on NT */
1319 NtDllModule = GetModuleHandle(TEXT("ntdll.dll"));
1320 }
1321 else
1322 {
1323 /* not all 9x versions have a ntdll.dll, try to load it */
1324 NtDllModule = LoadLibrary(TEXT("ntdll.dll"));
1325 }
1326
1327 if (NtDllModule != NULL)
1328 {
1329 NtQueryInformationProcessPtr = (NtQueryInformationProcessProc)GetProcAddress(NtDllModule, "NtQueryInformationProcess");
1330 NtReadVirtualMemoryPtr = (NtReadVirtualMemoryProc)GetProcAddress(NtDllModule, "NtReadVirtualMemory");
1331 }
1332
1333
1334 #ifdef _DEBUG
1335 INT x;
1336
1337 DebugPrintf (_T("[command args:\n"));
1338 for (x = 0; x < argc; x++)
1339 {
1340 DebugPrintf (_T("%d. %s\n"), x, argv[x]);
1341 }
1342 DebugPrintf (_T("]\n"));
1343 #endif
1344
1345 InitLocale ();
1346
1347 /* get default input and output console handles */
1348 hOut = GetStdHandle (STD_OUTPUT_HANDLE);
1349 hIn = GetStdHandle (STD_INPUT_HANDLE);
1350
1351
1352 if (argc >= 2 && !_tcsncmp (argv[1], _T("/?"), 2))
1353 {
1354 ConOutResPaging(TRUE,STRING_CMD_HELP8);
1355 ExitProcess(0);
1356 }
1357 SetConsoleMode (hIn, ENABLE_PROCESSED_INPUT);
1358
1359 #ifdef INCLUDE_CMD_CHDIR
1360 InitLastPath ();
1361 #endif
1362
1363 #ifdef FATURE_ALIASES
1364 InitializeAlias ();
1365 #endif
1366
1367 if (argc >= 2)
1368 {
1369 for (i = 1; i < argc; i++)
1370 {
1371 if (!_tcsicmp (argv[i], _T("/p")))
1372 {
1373 if (!IsExistingFile (_T("\\autoexec.bat")))
1374 {
1375 #ifdef INCLUDE_CMD_DATE
1376 cmd_date (_T(""), _T(""));
1377 #endif
1378 #ifdef INCLUDE_CMD_TIME
1379 cmd_time (_T(""), _T(""));
1380 #endif
1381 }
1382 else
1383 {
1384 ParseCommandLine (_T("\\autoexec.bat"));
1385 }
1386 bCanExit = FALSE;
1387 }
1388 else if (!_tcsicmp (argv[i], _T("/c")))
1389 {
1390 /* This just runs a program and exits */
1391 ++i;
1392 if (i < argc)
1393 {
1394 _tcscpy (commandline, argv[i]);
1395 while (++i < argc)
1396 {
1397 _tcscat (commandline, _T(" "));
1398 _tcscat (commandline, argv[i]);
1399 }
1400
1401 ParseCommandLine(commandline);
1402 ExitProcess (ProcessInput (TRUE));
1403 }
1404 else
1405 {
1406 ExitProcess (0);
1407 }
1408 }
1409 else if (!_tcsicmp (argv[i], _T("/k")))
1410 {
1411 /* This just runs a program and remains */
1412 ++i;
1413 if (i < argc)
1414 {
1415 _tcscpy (commandline, argv[i]);
1416 while (++i < argc)
1417 {
1418 _tcscat (commandline, _T(" "));
1419 _tcscat (commandline, argv[i]);
1420 }
1421
1422 ParseCommandLine(commandline);
1423 }
1424 }
1425 #ifdef INCLUDE_CMD_COLOR
1426 else if (!_tcsnicmp (argv[i], _T("/t:"), 3))
1427 {
1428 /* process /t (color) argument */
1429 wDefColor = (WORD)_tcstoul (&argv[i][3], NULL, 16);
1430 wColor = wDefColor;
1431 SetScreenColor (wColor, TRUE);
1432 }
1433 #endif
1434 }
1435 }
1436
1437 /* run cmdstart.bat */
1438 if (IsExistingFile (_T("cmdstart.bat")))
1439 {
1440 ParseCommandLine (_T("cmdstart.bat"));
1441 }
1442 else if (IsExistingFile (_T("\\cmdstart.bat")))
1443 {
1444 ParseCommandLine (_T("\\cmdstart.bat"));
1445 }
1446 #ifndef __REACTOS__
1447 else
1448 {
1449 /* try to run cmdstart.bat from install dir */
1450 LPTSTR p;
1451
1452 _tcscpy (commandline, argv[0]);
1453 p = _tcsrchr (commandline, _T('\\')) + 1;
1454 _tcscpy (p, _T("cmdstart.bat"));
1455
1456 if (IsExistingFile (_T("commandline")))
1457 {
1458 LoadString(CMD_ModuleHandle, STRING_CMD_ERROR4, szMsg, RC_STRING_MAX_SIZE);
1459 ConErrPrintf(szMsg, commandline);
1460 ParseCommandLine (commandline);
1461 }
1462 }
1463 #endif
1464
1465 #ifdef FEATURE_DIR_STACK
1466 /* initialize directory stack */
1467 InitDirectoryStack ();
1468 #endif
1469
1470
1471 #ifdef FEATURE_HISTORY
1472 /*initialize history*/
1473 InitHistory();
1474 #endif
1475
1476 /* Set COMSPEC environment variable */
1477 if (0 != GetModuleFileName (NULL, ModuleName, _MAX_PATH + 1))
1478 {
1479 ModuleName[_MAX_PATH] = _T('\0');
1480 SetEnvironmentVariable (_T("COMSPEC"), ModuleName);
1481 }
1482
1483 /* add ctrl break handler */
1484 AddBreakHandler ();
1485 }
1486
1487
1488 static VOID Cleanup (int argc, TCHAR *argv[])
1489 {
1490 #ifndef __REACTOS__
1491 TCHAR szMsg[RC_STRING_MAX_SIZE];
1492 #endif
1493
1494 /* run cmdexit.bat */
1495 if (IsExistingFile (_T("cmdexit.bat")))
1496 {
1497 ConErrResPuts(STRING_CMD_ERROR5);
1498
1499 ParseCommandLine (_T("cmdexit.bat"));
1500 }
1501 else if (IsExistingFile (_T("\\cmdexit.bat")))
1502 {
1503 ConErrResPuts (STRING_CMD_ERROR5);
1504 ParseCommandLine (_T("\\cmdexit.bat"));
1505 }
1506 #ifndef __REACTOS__
1507 else
1508 {
1509 /* try to run cmdexit.bat from install dir */
1510 TCHAR commandline[CMDLINE_LENGTH];
1511 LPTSTR p;
1512
1513 _tcscpy (commandline, argv[0]);
1514 p = _tcsrchr (commandline, _T('\\')) + 1;
1515 _tcscpy (p, _T("cmdexit.bat"));
1516
1517 if (IsExistingFile (_T("commandline")))
1518 {
1519 LoadString(CMD_ModuleHandle, STRING_CMD_ERROR4, szMsg, RC_STRING_MAX_SIZE);
1520 ConErrPrintf(szMsg, commandline);
1521 ParseCommandLine (commandline);
1522 }
1523 }
1524 #endif
1525
1526 #ifdef FEATURE_ALIASES
1527 DestroyAlias ();
1528 #endif
1529
1530 #ifdef FEATURE_DIECTORY_STACK
1531 /* destroy directory stack */
1532 DestroyDirectoryStack ();
1533 #endif
1534
1535 #ifdef INCLUDE_CMD_CHDIR
1536 FreeLastPath ();
1537 #endif
1538
1539 #ifdef FEATURE_HISTORY
1540 CleanHistory();
1541 #endif
1542
1543
1544 /* remove ctrl break handler */
1545 RemoveBreakHandler ();
1546 SetConsoleMode( GetStdHandle( STD_INPUT_HANDLE ),
1547 ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT | ENABLE_ECHO_INPUT );
1548
1549 if (NtDllModule != NULL)
1550 {
1551 FreeLibrary(NtDllModule);
1552 }
1553 }
1554
1555 #ifdef __REACTOS__
1556 #ifdef _UNICODE
1557 PWCHAR * _CommandLineToArgvW(PWCHAR lpCmdLine, int *pNumArgs)
1558 {
1559 PWCHAR * argvw = NULL;
1560 PWCHAR ptr = lpCmdLine;
1561 PWCHAR str;
1562 int len;
1563 int NumArgs;
1564
1565 NumArgs = 0;
1566
1567 while(lpCmdLine && *lpCmdLine)
1568 {
1569 while (iswspace(*lpCmdLine)) lpCmdLine++;
1570 if (*lpCmdLine)
1571 {
1572 if ((NumArgs % 10)==0)
1573 {
1574 PWCHAR * old_argvw = argvw;
1575 argvw = malloc((NumArgs + 10) * sizeof(PWCHAR));
1576 memcpy(argvw, old_argvw, NumArgs * sizeof(PWCHAR));
1577 free(old_argvw);
1578 }
1579 ptr = wcschr(lpCmdLine, L' ');
1580 if (ptr)
1581 {
1582 len = ptr - lpCmdLine;
1583 }
1584 else
1585 {
1586 len = wcslen(lpCmdLine);
1587 }
1588 str = malloc((len + 1) * sizeof(WCHAR));
1589 memcpy(str, lpCmdLine, len * sizeof(WCHAR));
1590 str[len] = 0;
1591 argvw[NumArgs]=str;
1592 NumArgs++;
1593 lpCmdLine = ptr;
1594 }
1595 }
1596 *pNumArgs = NumArgs;
1597 return argvw;
1598 }
1599 #endif
1600 #endif
1601
1602 /*
1603 * main function
1604 */
1605 #ifdef _UNICODE
1606 int _main(void)
1607 #else
1608 int _main (int argc, char *argv[])
1609 #endif
1610 {
1611 TCHAR startPath[MAX_PATH];
1612 CONSOLE_SCREEN_BUFFER_INFO Info;
1613 INT nExitCode;
1614 #ifdef _UNICODE
1615 PWCHAR * argv;
1616 int argc=0;
1617 #ifdef __REACTOS__
1618 argv = _CommandLineToArgvW(GetCommandLineW(), &argc);
1619 #else
1620 argv = CommandLineToArgvW(GetCommandLineW(), &argc);
1621 #endif
1622 #endif
1623
1624 GetCurrentDirectory(MAX_PATH,startPath);
1625 _tchdir(startPath);
1626
1627 SetFileApisToOEM();
1628 InputCodePage= 0;
1629 OutputCodePage = 0;
1630
1631 hConsole = CreateFile(_T("CONOUT$"), GENERIC_READ|GENERIC_WRITE,
1632 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL,
1633 OPEN_EXISTING, 0, NULL);
1634 if (GetConsoleScreenBufferInfo(hConsole, &Info) == FALSE)
1635 {
1636 ConErrFormatMessage(GetLastError());
1637 return(1);
1638 }
1639 wColor = Info.wAttributes;
1640 wDefColor = wColor;
1641
1642 InputCodePage= GetConsoleCP();
1643 OutputCodePage = GetConsoleOutputCP();
1644 CMD_ModuleHandle = GetModuleHandle(NULL);
1645
1646 /* check switches on command-line */
1647 Initialize(argc, argv);
1648
1649 /* call prompt routine */
1650 nExitCode = ProcessInput(FALSE);
1651
1652
1653 /* do the cleanup */
1654 Cleanup(argc, argv);
1655
1656
1657 return(nExitCode);
1658 }
1659
1660 /* EOF */