Correctly assign %propmt%.
[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 /* %TIME% */
1081 else if (_tcsicmp(ip,_T("time")) ==0)
1082 {
1083 TCHAR szTime[40];
1084 SYSTEMTIME t;
1085 GetSystemTime(&t);
1086
1087 _sntprintf(szTime ,40,_T("%02d%c%02d%c%02d%c%02d"), t.wHour, cTimeSeparator,t.wMinute , cTimeSeparator,t.wSecond , cDecimalSeparator, t.wMilliseconds );
1088 cp = _stpcpy (cp, szTime);
1089 }
1090
1091 /* %DATE% */
1092 else if (_tcsicmp(ip,_T("date")) ==0)
1093 {
1094 TCHAR szDate[40];
1095
1096 GetDateFormat(LOCALE_USER_DEFAULT, 0, NULL, _T("ddd"), szDate, sizeof (szDate));
1097 cp = _stpcpy (cp, szDate);
1098 cp = _stpcpy (cp, _T(" "));
1099 GetDateFormat(LOCALE_USER_DEFAULT, DATE_SHORTDATE, NULL, NULL, szDate, sizeof (szDate));
1100 cp = _stpcpy (cp, szDate);
1101 }
1102
1103 /* %RANDOM% */
1104 else if (_tcsicmp(ip,_T("random")) ==0)
1105 {
1106 TCHAR szRand[40];
1107 /* Get random number */
1108 _itot(rand(),szRand,10);
1109 cp = _stpcpy (cp, szRand);
1110 }
1111
1112 /* %CMDCMDLINE% */
1113 else if (_tcsicmp(ip,_T("cmdcmdline")) ==0)
1114 {
1115 TCHAR *pargv;
1116 /* Get random number */
1117 pargv = GetCommandLine();
1118 cp = _stpcpy (cp, pargv);
1119 }
1120
1121 /* %CMDEXTVERSION% */
1122 else if (_tcsicmp(ip,_T("cmdextversion")) ==0)
1123 {
1124 TCHAR szVER[40];
1125 /* Set version number to 2 */
1126 _itot(2,szVER,10);
1127 cp = _stpcpy (cp, szVER);
1128 }
1129
1130 /* %ERRORLEVEL% */
1131 else if (_tcsicmp(ip,_T("errorlevel")) ==0)
1132 {
1133 evar = malloc ( size * sizeof(TCHAR));
1134 if (evar==NULL)
1135 return 1;
1136
1137 memset(evar,0,512 * sizeof(TCHAR));
1138 _itot(nErrorLevel,evar,10);
1139 cp = _stpcpy (cp, evar);
1140
1141 free(evar);
1142 }
1143 else
1144 {
1145 evar = malloc ( 512 * sizeof(TCHAR));
1146 if (evar==NULL)
1147 return 1;
1148 SetLastError(0);
1149 size = GetEnvironmentVariable (ip, evar, 512);
1150 if(GetLastError() == ERROR_ENVVAR_NOT_FOUND)
1151 {
1152 /* if no env var is found you must
1153 continue with what was input*/
1154 cp = _stpcpy (cp, _T("%"));
1155 cp = _stpcpy (cp, ip);
1156 cp = _stpcpy (cp, _T("%"));
1157 }
1158 else
1159 {
1160 if (size > 512)
1161 {
1162 evar = realloc(evar,size * sizeof(TCHAR) );
1163 if (evar==NULL)
1164 {
1165 return 1;
1166 }
1167 size = GetEnvironmentVariable (ip, evar, size);
1168 }
1169
1170 if (size)
1171 {
1172 cp = _stpcpy (cp, evar);
1173 }
1174 }
1175
1176 free(evar);
1177 }
1178
1179 ip = tp + 1;
1180
1181 }
1182 else
1183 {
1184 *cp++ = _T('%');
1185 }
1186
1187 break;
1188 }
1189 continue;
1190 }
1191
1192
1193
1194
1195 if (_istcntrl (*ip))
1196 *ip = _T(' ');
1197 *cp++ = *ip++;
1198 }
1199
1200 *cp = _T('\0');
1201
1202 /* strip trailing spaces */
1203 while ((--cp >= commandline) && _istspace (*cp));
1204
1205 *(cp + 1) = _T('\0');
1206
1207 /* JPP 19980807 */
1208 /* Echo batch file line */
1209 if (bEchoThisLine)
1210 {
1211 PrintPrompt ();
1212 ConOutPuts (commandline);
1213 }
1214
1215 if (*commandline)
1216 {
1217 ParseCommandLine (commandline);
1218 if (bEcho && !bIgnoreEcho)
1219 ConOutChar ('\n');
1220 bIgnoreEcho = FALSE;
1221 }
1222 }
1223 while (!bCanExit || !bExit);
1224
1225 return 0;
1226 }
1227
1228
1229 /*
1230 * control-break handler.
1231 */
1232 BOOL WINAPI BreakHandler (DWORD dwCtrlType)
1233 {
1234
1235 if ((dwCtrlType != CTRL_C_EVENT) &&
1236 (dwCtrlType != CTRL_BREAK_EVENT))
1237 return FALSE;
1238
1239 if (bChildProcessRunning == TRUE)
1240 {
1241 GenerateConsoleCtrlEvent (CTRL_C_EVENT,
1242 dwChildProcessId);
1243 return TRUE;
1244 }
1245
1246 /* FIXME: Handle batch files */
1247
1248 /* FIXME: Print "^C" */
1249
1250
1251 return TRUE;
1252 }
1253
1254
1255 VOID AddBreakHandler (VOID)
1256 {
1257 SetConsoleCtrlHandler ((PHANDLER_ROUTINE)BreakHandler, TRUE);
1258 }
1259
1260
1261 VOID RemoveBreakHandler (VOID)
1262 {
1263 SetConsoleCtrlHandler ((PHANDLER_ROUTINE)BreakHandler, FALSE);
1264 }
1265
1266
1267 /*
1268 * show commands and options that are available.
1269 *
1270 */
1271 #if 0
1272 static VOID
1273 ShowCommands (VOID)
1274 {
1275 /* print command list */
1276 ConOutResPuts(STRING_CMD_HELP1);
1277 PrintCommandList();
1278
1279 /* print feature list */
1280 ConOutResPuts(STRING_CMD_HELP2);
1281
1282 #ifdef FEATURE_ALIASES
1283 ConOutResPuts(STRING_CMD_HELP3);
1284 #endif
1285 #ifdef FEATURE_HISTORY
1286 ConOutResPuts(STRING_CMD_HELP4);
1287 #endif
1288 #ifdef FEATURE_UNIX_FILENAME_COMPLETION
1289 ConOutResPuts(STRING_CMD_HELP5);
1290 #endif
1291 #ifdef FEATURE_DIRECTORY_STACK
1292 ConOutResPuts(STRING_CMD_HELP6);
1293 #endif
1294 #ifdef FEATURE_REDIRECTION
1295 ConOutResPuts(STRING_CMD_HELP7);
1296 #endif
1297 ConOutChar(_T('\n'));
1298 }
1299 #endif
1300
1301 /*
1302 * set up global initializations and process parameters
1303 *
1304 * argc - number of parameters to command.com
1305 * argv - command-line parameters
1306 *
1307 */
1308 static VOID
1309 Initialize (int argc, TCHAR* argv[])
1310 {
1311 TCHAR commandline[CMDLINE_LENGTH];
1312 TCHAR ModuleName[_MAX_PATH + 1];
1313 INT i;
1314
1315 //INT len;
1316 //TCHAR *ptr, *cmdLine;
1317
1318 /* get version information */
1319 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
1320 GetVersionEx (&osvi);
1321
1322 /* Some people like to run ReactOS cmd.exe on Win98, it helps in the
1323 build process. So don't link implicitly against ntdll.dll, load it
1324 dynamically instead */
1325
1326 if (osvi.dwPlatformId == VER_PLATFORM_WIN32_NT)
1327 {
1328 /* ntdll is always present on NT */
1329 NtDllModule = GetModuleHandle(TEXT("ntdll.dll"));
1330 }
1331 else
1332 {
1333 /* not all 9x versions have a ntdll.dll, try to load it */
1334 NtDllModule = LoadLibrary(TEXT("ntdll.dll"));
1335 }
1336
1337 if (NtDllModule != NULL)
1338 {
1339 NtQueryInformationProcessPtr = (NtQueryInformationProcessProc)GetProcAddress(NtDllModule, "NtQueryInformationProcess");
1340 NtReadVirtualMemoryPtr = (NtReadVirtualMemoryProc)GetProcAddress(NtDllModule, "NtReadVirtualMemory");
1341 }
1342
1343
1344 #ifdef _DEBUG
1345 INT x;
1346
1347 DebugPrintf (_T("[command args:\n"));
1348 for (x = 0; x < argc; x++)
1349 {
1350 DebugPrintf (_T("%d. %s\n"), x, argv[x]);
1351 }
1352 DebugPrintf (_T("]\n"));
1353 #endif
1354
1355 InitLocale ();
1356
1357 /* get default input and output console handles */
1358 hOut = GetStdHandle (STD_OUTPUT_HANDLE);
1359 hIn = GetStdHandle (STD_INPUT_HANDLE);
1360
1361 SetEnvironmentVariable (_T("PROMPT"), _T("$P$G"));
1362
1363
1364 if (argc >= 2 && !_tcsncmp (argv[1], _T("/?"), 2))
1365 {
1366 ConOutResPaging(TRUE,STRING_CMD_HELP8);
1367 ExitProcess(0);
1368 }
1369 SetConsoleMode (hIn, ENABLE_PROCESSED_INPUT);
1370
1371 #ifdef INCLUDE_CMD_CHDIR
1372 InitLastPath ();
1373 #endif
1374
1375 #ifdef FATURE_ALIASES
1376 InitializeAlias ();
1377 #endif
1378
1379 if (argc >= 2)
1380 {
1381 for (i = 1; i < argc; i++)
1382 {
1383 if (!_tcsicmp (argv[i], _T("/p")))
1384 {
1385 if (!IsExistingFile (_T("\\autoexec.bat")))
1386 {
1387 #ifdef INCLUDE_CMD_DATE
1388 cmd_date (_T(""), _T(""));
1389 #endif
1390 #ifdef INCLUDE_CMD_TIME
1391 cmd_time (_T(""), _T(""));
1392 #endif
1393 }
1394 else
1395 {
1396 ParseCommandLine (_T("\\autoexec.bat"));
1397 }
1398 bCanExit = FALSE;
1399 }
1400 else if (!_tcsicmp (argv[i], _T("/c")))
1401 {
1402 /* This just runs a program and exits */
1403 ++i;
1404 if (i < argc)
1405 {
1406 _tcscpy (commandline, argv[i]);
1407 while (++i < argc)
1408 {
1409 _tcscat (commandline, _T(" "));
1410 _tcscat (commandline, argv[i]);
1411 }
1412
1413 ParseCommandLine(commandline);
1414 ExitProcess (ProcessInput (TRUE));
1415 }
1416 else
1417 {
1418 ExitProcess (0);
1419 }
1420 }
1421 else if (!_tcsicmp (argv[i], _T("/k")))
1422 {
1423 /* This just runs a program and remains */
1424 ++i;
1425 if (i < argc)
1426 {
1427 _tcscpy (commandline, argv[i]);
1428 while (++i < argc)
1429 {
1430 _tcscat (commandline, _T(" "));
1431 _tcscat (commandline, argv[i]);
1432 }
1433
1434 ParseCommandLine(commandline);
1435 }
1436 }
1437 #ifdef INCLUDE_CMD_COLOR
1438 else if (!_tcsnicmp (argv[i], _T("/t:"), 3))
1439 {
1440 /* process /t (color) argument */
1441 wDefColor = (WORD)_tcstoul (&argv[i][3], NULL, 16);
1442 wColor = wDefColor;
1443 SetScreenColor (wColor, TRUE);
1444 }
1445 #endif
1446 }
1447 }
1448
1449 /* run cmdstart.bat */
1450 if (IsExistingFile (_T("cmdstart.bat")))
1451 {
1452 ParseCommandLine (_T("cmdstart.bat"));
1453 }
1454 else if (IsExistingFile (_T("\\cmdstart.bat")))
1455 {
1456 ParseCommandLine (_T("\\cmdstart.bat"));
1457 }
1458 #ifndef __REACTOS__
1459 else
1460 {
1461 /* try to run cmdstart.bat from install dir */
1462 LPTSTR p;
1463
1464 _tcscpy (commandline, argv[0]);
1465 p = _tcsrchr (commandline, _T('\\')) + 1;
1466 _tcscpy (p, _T("cmdstart.bat"));
1467
1468 if (IsExistingFile (_T("commandline")))
1469 {
1470 LoadString(CMD_ModuleHandle, STRING_CMD_ERROR4, szMsg, RC_STRING_MAX_SIZE);
1471 ConErrPrintf(szMsg, commandline);
1472 ParseCommandLine (commandline);
1473 }
1474 }
1475 #endif
1476
1477 #ifdef FEATURE_DIR_STACK
1478 /* initialize directory stack */
1479 InitDirectoryStack ();
1480 #endif
1481
1482
1483 #ifdef FEATURE_HISTORY
1484 /*initialize history*/
1485 InitHistory();
1486 #endif
1487
1488 /* Set COMSPEC environment variable */
1489 if (0 != GetModuleFileName (NULL, ModuleName, _MAX_PATH + 1))
1490 {
1491 ModuleName[_MAX_PATH] = _T('\0');
1492 SetEnvironmentVariable (_T("COMSPEC"), ModuleName);
1493 }
1494
1495 /* add ctrl break handler */
1496 AddBreakHandler ();
1497 }
1498
1499
1500 static VOID Cleanup (int argc, TCHAR *argv[])
1501 {
1502 #ifndef __REACTOS__
1503 TCHAR szMsg[RC_STRING_MAX_SIZE];
1504 #endif
1505
1506 /* run cmdexit.bat */
1507 if (IsExistingFile (_T("cmdexit.bat")))
1508 {
1509 ConErrResPuts(STRING_CMD_ERROR5);
1510
1511 ParseCommandLine (_T("cmdexit.bat"));
1512 }
1513 else if (IsExistingFile (_T("\\cmdexit.bat")))
1514 {
1515 ConErrResPuts (STRING_CMD_ERROR5);
1516 ParseCommandLine (_T("\\cmdexit.bat"));
1517 }
1518 #ifndef __REACTOS__
1519 else
1520 {
1521 /* try to run cmdexit.bat from install dir */
1522 TCHAR commandline[CMDLINE_LENGTH];
1523 LPTSTR p;
1524
1525 _tcscpy (commandline, argv[0]);
1526 p = _tcsrchr (commandline, _T('\\')) + 1;
1527 _tcscpy (p, _T("cmdexit.bat"));
1528
1529 if (IsExistingFile (_T("commandline")))
1530 {
1531 LoadString(CMD_ModuleHandle, STRING_CMD_ERROR4, szMsg, RC_STRING_MAX_SIZE);
1532 ConErrPrintf(szMsg, commandline);
1533 ParseCommandLine (commandline);
1534 }
1535 }
1536 #endif
1537
1538 #ifdef FEATURE_ALIASES
1539 DestroyAlias ();
1540 #endif
1541
1542 #ifdef FEATURE_DIECTORY_STACK
1543 /* destroy directory stack */
1544 DestroyDirectoryStack ();
1545 #endif
1546
1547 #ifdef INCLUDE_CMD_CHDIR
1548 FreeLastPath ();
1549 #endif
1550
1551 #ifdef FEATURE_HISTORY
1552 CleanHistory();
1553 #endif
1554
1555
1556 /* remove ctrl break handler */
1557 RemoveBreakHandler ();
1558 SetConsoleMode( GetStdHandle( STD_INPUT_HANDLE ),
1559 ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT | ENABLE_ECHO_INPUT );
1560
1561 if (NtDllModule != NULL)
1562 {
1563 FreeLibrary(NtDllModule);
1564 }
1565 }
1566
1567 #ifdef __REACTOS__
1568 #ifdef _UNICODE
1569 PWCHAR * _CommandLineToArgvW(PWCHAR lpCmdLine, int *pNumArgs)
1570 {
1571 PWCHAR * argvw = NULL;
1572 PWCHAR ptr = lpCmdLine;
1573 PWCHAR str;
1574 int len;
1575 int NumArgs;
1576
1577 NumArgs = 0;
1578
1579 while(lpCmdLine && *lpCmdLine)
1580 {
1581 while (iswspace(*lpCmdLine)) lpCmdLine++;
1582 if (*lpCmdLine)
1583 {
1584 if ((NumArgs % 10)==0)
1585 {
1586 PWCHAR * old_argvw = argvw;
1587 argvw = malloc((NumArgs + 10) * sizeof(PWCHAR));
1588 memcpy(argvw, old_argvw, NumArgs * sizeof(PWCHAR));
1589 free(old_argvw);
1590 }
1591 ptr = wcschr(lpCmdLine, L' ');
1592 if (ptr)
1593 {
1594 len = ptr - lpCmdLine;
1595 }
1596 else
1597 {
1598 len = wcslen(lpCmdLine);
1599 }
1600 str = malloc((len + 1) * sizeof(WCHAR));
1601 memcpy(str, lpCmdLine, len * sizeof(WCHAR));
1602 str[len] = 0;
1603 argvw[NumArgs]=str;
1604 NumArgs++;
1605 lpCmdLine = ptr;
1606 }
1607 }
1608 *pNumArgs = NumArgs;
1609 return argvw;
1610 }
1611 #endif
1612 #endif
1613
1614 /*
1615 * main function
1616 */
1617 #ifdef _UNICODE
1618 int _main(void)
1619 #else
1620 int _main (int argc, char *argv[])
1621 #endif
1622 {
1623 TCHAR startPath[MAX_PATH];
1624 CONSOLE_SCREEN_BUFFER_INFO Info;
1625 INT nExitCode;
1626 #ifdef _UNICODE
1627 PWCHAR * argv;
1628 int argc=0;
1629 #ifdef __REACTOS__
1630 argv = _CommandLineToArgvW(GetCommandLineW(), &argc);
1631 #else
1632 argv = CommandLineToArgvW(GetCommandLineW(), &argc);
1633 #endif
1634 #endif
1635
1636 GetCurrentDirectory(MAX_PATH,startPath);
1637 _tchdir(startPath);
1638
1639 SetFileApisToOEM();
1640 InputCodePage= 0;
1641 OutputCodePage = 0;
1642
1643 hConsole = CreateFile(_T("CONOUT$"), GENERIC_READ|GENERIC_WRITE,
1644 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL,
1645 OPEN_EXISTING, 0, NULL);
1646 if (GetConsoleScreenBufferInfo(hConsole, &Info) == FALSE)
1647 {
1648 ConErrFormatMessage(GetLastError());
1649 return(1);
1650 }
1651 wColor = Info.wAttributes;
1652 wDefColor = wColor;
1653
1654 InputCodePage= GetConsoleCP();
1655 OutputCodePage = GetConsoleOutputCP();
1656 CMD_ModuleHandle = GetModuleHandle(NULL);
1657
1658 /* check switches on command-line */
1659 Initialize(argc, argv);
1660
1661 /* call prompt routine */
1662 nExitCode = ProcessInput(FALSE);
1663
1664
1665 /* do the cleanup */
1666 Cleanup(argc, argv);
1667
1668
1669 return(nExitCode);
1670 }
1671
1672 /* EOF */