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