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