2 * CMD.C - command-line interface.
7 * 17 Jun 1994 (Tim Norman)
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.
14 * A added the the standard FreeDOS GNU licence test to the
15 * initialize() function.
17 * Started to replace puts() with printf(). this will help
18 * standardize output. please follow my lead.
20 * I have added some constants to help making changes easier.
22 * 15 Dec 1995 (Tim Norman)
23 * major rewrite of the code to make it more efficient and add
24 * redirection support (finally!)
26 * 06 Jan 1996 (Tim Norman)
27 * finished adding redirection support! Changed to use our own
28 * exec code (MUCH thanks to Svante Frey!!)
30 * 29 Jan 1996 (Tim Norman)
31 * added support for CHDIR, RMDIR, MKDIR, and ERASE, as per
32 * suggestion of Steffan Kaiser
34 * changed "file not found" error message to "bad command or
35 * filename" thanks to Dustin Norman for noticing that confusing
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)
42 * 27 Aug 1996 (Tim Norman)
43 * added in support for Oliver Mueller's ALIAS command
45 * 14 Jun 1997 (Steffan Kaiser)
46 * added ctrl-break handling and error level
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.
53 * 21 Jun 1998 (Rob Lake)
54 * Fixed up /C so that arguments for the program
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!
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.
68 * New organisation also properly support nested batch files.
70 * New command table structure is half way towards providing a
71 * system in which COMMAND will find out what internal commands
74 * 24 Jul 1998 (Hans B Pufal) [HBP_003]
75 * Fixed return value when called with /C option
77 * 27 Jul 1998 John P. Price
78 * added config.h include
80 * 28 Jul 1998 John P. Price
81 * added showcmds function to show commands and options available
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")
87 * 07-Dec-1998 (Eric Kohl)
88 * First ReactOS release.
89 * Extended length of commandline buffers to 512.
91 * 13-Dec-1998 (Eric Kohl)
92 * Added COMSPEC environment variable.
93 * Added "/t" support (color) on cmd command line.
95 * 07-Jan-1999 (Eric Kohl)
96 * Added help text ("cmd /?").
98 * 25-Jan-1999 (Eric Kohl)
99 * Unicode and redirection safe!
100 * Fixed redirections and piping.
101 * Piping is based on temporary files, but basic support
102 * for anonymous pipes already exists.
104 * 27-Jan-1999 (Eric Kohl)
105 * Replaced spawnl() by CreateProcess().
107 * 22-Oct-1999 (Eric Kohl)
108 * Added break handler.
110 * 15-Dec-1999 (Eric Kohl)
111 * Fixed current directory
113 * 28-Dec-1999 (Eric Kohl)
114 * Restore window title after program/batch execution
116 * 03-Feb-2001 (Eric Kohl)
117 * Workaround because argc[0] is NULL under ReactOS
119 * 23-Feb-2001 (Carl Nettelblad <cnettel@hem.passagen.se>)
120 * %envvar% replacement conflicted with for.
122 * 30-Apr-2004 (Filip Navara <xnavara@volny.cz>)
123 * Make MakeSureDirectoryPathExistsEx unicode safe.
126 * Removed MakeSureDirectoryPathExistsEx.
127 * Use the current directory if GetTempPath fails.
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.
132 * 02-Apr-2005 (Magnus Olsen <magnus@greatlord.com>)
133 * Remove all hardcode string to En.rc
135 * 06-May-2005 (Klemens Friedl <frik85@gmail.com>)
136 * Add 'help' command (list all commands plus description)
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
147 #define NT_SUCCESS(StatCode) ((NTSTATUS)(StatCode) >= 0)
150 typedef NTSTATUS (WINAPI
*NtQueryInformationProcessProc
)(HANDLE
, PROCESSINFOCLASS
,
151 PVOID
, ULONG
, PULONG
);
152 typedef NTSTATUS (WINAPI
*NtReadVirtualMemoryProc
)(HANDLE
, PVOID
, PVOID
, ULONG
, PULONG
);
154 BOOL bExit
= FALSE
; /* indicates EXIT was typed */
155 BOOL bCanExit
= TRUE
; /* indicates if this shell is exitable */
156 BOOL bCtrlBreak
= FALSE
; /* Ctrl-Break or Ctrl-C hit */
157 BOOL bIgnoreEcho
= FALSE
; /* Ignore 'newline' before 'cls' */
158 INT nErrorLevel
= 0; /* Errorlevel of last launched external program */
159 BOOL bChildProcessRunning
= FALSE
;
160 DWORD dwChildProcessId
= 0;
165 HANDLE CMD_ModuleHandle
;
168 static NtQueryInformationProcessProc NtQueryInformationProcessPtr
= NULL
;
169 static NtReadVirtualMemoryProc NtReadVirtualMemoryPtr
= NULL
;
171 #ifdef INCLUDE_CMD_COLOR
172 WORD wColor
; /* current color */
173 WORD wDefColor
; /* default color */
179 * insert commas into a number
182 ConvertULargeInteger (ULARGE_INTEGER num
, LPTSTR des
, INT len
, BOOL bPutSeperator
)
191 if (num
.QuadPart
== 0)
200 while (num
.QuadPart
> 0)
202 if ((((c
+ 1) % (nNumberGroups
+ 1)) == 0) && (bPutSeperator
))
203 temp
[30 - c
++] = cThousandSeparator
;
204 temp
[30 - c
++] = (TCHAR
)(num
.QuadPart
% 10) + _T('0');
210 for (n
= 0; n
<= c
; n
++)
211 des
[n
] = temp
[31 - c
+ n
];
218 * is character a delimeter when used on first word?
221 static BOOL
IsDelimiter (TCHAR c
)
223 return (c
== _T('/') || c
== _T('=') || c
== _T('\0') || _istspace (c
));
227 * Is a process a console process?
229 static BOOL
IsConsoleProcess(HANDLE Process
)
232 PROCESS_BASIC_INFORMATION Info
;
236 if (NULL
== NtQueryInformationProcessPtr
|| NULL
== NtReadVirtualMemoryPtr
)
241 Status
= NtQueryInformationProcessPtr (
242 Process
, ProcessBasicInformation
,
243 &Info
, sizeof(PROCESS_BASIC_INFORMATION
), NULL
);
244 if (! NT_SUCCESS(Status
))
247 DebugPrintf (_T("NtQueryInformationProcess failed with status %08x\n"), Status
);
251 Status
= NtReadVirtualMemoryPtr (
252 Process
, Info
.PebBaseAddress
, &ProcessPeb
,
253 sizeof(PEB
), &BytesRead
);
254 if (! NT_SUCCESS(Status
) || sizeof(PEB
) != BytesRead
)
257 DebugPrintf (_T("Couldn't read virt mem status %08x bytes read %lu\n"), Status
, BytesRead
);
262 return IMAGE_SUBSYSTEM_WINDOWS_CUI
== ProcessPeb
.ImageSubSystem
;
268 #define SHELLEXECUTETEXT "ShellExecuteW"
270 #define SHELLEXECUTETEXT "ShellExecuteA"
273 typedef HINSTANCE (WINAPI
*MYEX
)(
277 LPCTSTR lpParameters
,
284 static BOOL
RunFile(LPTSTR filename
)
291 DebugPrintf (_T("RunFile(%s)\n"), filename
);
293 hShell32
= LoadLibrary(_T("SHELL32.DLL"));
297 DebugPrintf (_T("RunFile: couldn't load SHELL32.DLL!\n"));
302 hShExt
= (MYEX
)(FARPROC
)GetProcAddress(hShell32
, SHELLEXECUTETEXT
);
306 DebugPrintf (_T("RunFile: couldn't find ShellExecuteA/W in SHELL32.DLL!\n"));
308 FreeLibrary(hShell32
);
313 DebugPrintf (_T("RunFile: ShellExecuteA/W is at %x\n"), hShExt
);
316 ret
= (hShExt
)(NULL
, _T("open"), filename
, NULL
, NULL
, SW_SHOWNORMAL
);
319 DebugPrintf (_T("RunFile: ShellExecuteA/W returned %d\n"), (DWORD
)ret
);
322 FreeLibrary(hShell32
);
323 return (((DWORD
)ret
) > 32);
329 * This command (in first) was not found in the command table
331 * Full - whole command line
332 * First - first word on command line
333 * Rest - rest of command line
337 Execute (LPTSTR Full
, LPTSTR First
, LPTSTR Rest
)
339 TCHAR
*szFullName
=NULL
;
344 TCHAR szWindowTitle
[MAX_PATH
];
345 DWORD dwExitCode
= 0;
348 DebugPrintf (_T("Execute: \'%s\' \'%s\'\n"), first
, rest
);
351 /* we need biger buffer that First, Rest, Full are already
352 need rewrite some code to use cmd_realloc when it need instead
353 of add 512bytes extra */
355 first
= cmd_alloc ( (_tcslen(First
) + 512) * sizeof(TCHAR
));
358 error_out_of_memory();
363 rest
= cmd_alloc ( (_tcslen(Rest
) + 512) * sizeof(TCHAR
));
367 error_out_of_memory();
372 full
= cmd_alloc ( (_tcslen(Full
) + 512) * sizeof(TCHAR
));
377 error_out_of_memory();
382 szFullName
= cmd_alloc ( (_tcslen(Full
) + 512) * sizeof(TCHAR
));
388 error_out_of_memory();
394 /* Though it was already parsed once, we have a different set of rules
395 for parsing before we pass to CreateProccess */
396 if(!_tcschr(Full
,_T('\"')))
398 _tcscpy(first
,First
);
405 BOOL bInside
= FALSE
;
410 /* find the end of the command and start of the args */
411 for(i
= 0; i
< _tcslen(first
); i
++)
413 if(!_tcsncmp(&first
[i
], _T("\""), 1))
415 if(!_tcsncmp(&first
[i
], _T(" "), 1) && !bInside
)
417 _tcscpy(rest
,&first
[i
]);
424 /* remove any slashes */
425 while(i
< _tcslen(first
))
427 if(first
[i
] == _T('\"'))
428 memmove(&first
[i
],&first
[i
+ 1], _tcslen(&first
[i
]) * sizeof(TCHAR
));
432 /* Drop quotes around it just in case there is a space */
433 _tcscpy(full
,_T("\""));
435 _tcscat(full
,_T("\" "));
439 /* check for a drive change */
440 if ((_istalpha (first
[0])) && (!_tcscmp (first
+ 1, _T(":"))))
443 if (!SetCurrentDirectory(first
))
444 /* Guess they changed disc or something, handle that gracefully and get to root */
451 working
= SetCurrentDirectory(str
);
454 if (!working
) ConErrResPuts (STRING_FREE_ERROR1
);
459 cmd_free (szFullName
);
464 /* get the PATH environment variable and parse it */
465 /* search the PATH environment variable for the binary */
466 if (!SearchForExecutable (first
, szFullName
))
468 error_bad_command ();
472 cmd_free (szFullName
);
478 GetConsoleTitle (szWindowTitle
, MAX_PATH
);
480 /* check if this is a .BAT or .CMD file */
481 dot
= _tcsrchr (szFullName
, _T('.'));
482 if (dot
&& (!_tcsicmp (dot
, _T(".bat")) || !_tcsicmp (dot
, _T(".cmd"))))
485 DebugPrintf (_T("[BATCH: %s %s]\n"), szFullName
, rest
);
487 Batch (szFullName
, first
, rest
);
491 /* exec the program */
492 PROCESS_INFORMATION prci
;
496 DebugPrintf (_T("[EXEC: %s %s]\n"), full
, rest
);
498 /* build command line for CreateProcess() */
500 /* fill startup info */
501 memset (&stui
, 0, sizeof (STARTUPINFO
));
502 stui
.cb
= sizeof (STARTUPINFO
);
503 stui
.dwFlags
= STARTF_USESHOWWINDOW
;
504 stui
.wShowWindow
= SW_SHOWDEFAULT
;
506 // return console to standard mode
507 SetConsoleMode (GetStdHandle(STD_INPUT_HANDLE
),
508 ENABLE_LINE_INPUT
| ENABLE_PROCESSED_INPUT
| ENABLE_ECHO_INPUT
);
510 if (CreateProcess (szFullName
,
515 0, /* CREATE_NEW_PROCESS_GROUP */
522 if (IsConsoleProcess(prci
.hProcess
))
524 /* FIXME: Protect this with critical section */
525 bChildProcessRunning
= TRUE
;
526 dwChildProcessId
= prci
.dwProcessId
;
528 WaitForSingleObject (prci
.hProcess
, INFINITE
);
530 /* FIXME: Protect this with critical section */
531 bChildProcessRunning
= FALSE
;
533 GetExitCodeProcess (prci
.hProcess
, &dwExitCode
);
534 nErrorLevel
= (INT
)dwExitCode
;
540 CloseHandle (prci
.hThread
);
541 CloseHandle (prci
.hProcess
);
546 DebugPrintf (_T("[ShellExecute: %s]\n"), full
);
548 // See if we can run this with ShellExecute() ie myfile.xls
552 DebugPrintf (_T("[ShellExecute failed!: %s]\n"), full
);
554 error_bad_command ();
562 // restore console mode
564 GetStdHandle( STD_INPUT_HANDLE
),
565 ENABLE_PROCESSED_INPUT
);
568 /* Get code page if it has been change */
569 InputCodePage
= GetConsoleCP();
570 OutputCodePage
= GetConsoleOutputCP();
571 SetConsoleTitle (szWindowTitle
);
576 cmd_free (szFullName
);
581 * look through the internal commands and determine whether or not this
582 * command is one of them. If it is, call the command. If not, call
583 * execute to run it as an external program.
585 * line - the command line of the program to run
590 DoCommand (LPTSTR line
)
592 TCHAR
*com
= NULL
; /* the first word in the command */
595 LPTSTR rest
; /* pointer to the rest of the command line */
600 DebugPrintf (_T("DoCommand: (\'%s\')\n"), line
);
603 com
= cmd_alloc( (_tcslen(line
) +512)*sizeof(TCHAR
) );
606 error_out_of_memory();
611 /* Skip over initial white space */
612 while (_istspace (*line
))
618 /* Anything to do ? */
621 if (*rest
== _T('"'))
623 /* treat quoted words specially */
627 while(*rest
!= _T('\0') && *rest
!= _T('"'))
628 *cp
++ = _totlower (*rest
++);
629 if (*rest
== _T('"'))
634 while (!IsDelimiter (*rest
))
635 *cp
++ = _totlower (*rest
++);
639 /* Terminate first word */
642 /* Do not limit commands to MAX_PATH */
644 if(_tcslen(com) > MAX_PATH)
652 /* Skip over whitespace to rest of line, exclude 'echo' command */
653 if (_tcsicmp (com
, _T("echo")))
655 while (_istspace (*rest
))
659 /* Scan internal command table */
660 for (cmdptr
= cmds
;; cmdptr
++)
662 /* If end of table execute ext cmd */
663 if (cmdptr
->name
== NULL
)
665 Execute (line
, com
, rest
);
669 if (!_tcscmp (com
, cmdptr
->name
))
671 cmdptr
->func (com
, rest
);
675 /* The following code handles the case of commands like CD which
676 * are recognised even when the command name and parameter are
677 * not space separated.
683 /* Get length of command name */
684 cl
= _tcslen (cmdptr
->name
);
686 if ((cmdptr
->flags
& CMD_SPECIAL
) &&
687 (!_tcsncmp (cmdptr
->name
, com
, cl
)) &&
688 (_tcschr (_T("\\.-"), *(com
+ cl
))))
690 /* OK its one of the specials...*/
692 /* Terminate first word properly */
695 /* Call with new rest */
696 cmdptr
->func (com
, cstart
+ cl
);
706 * process the command line and execute the appropriate functions
707 * full input/output redirection and piping are supported
710 VOID
ParseCommandLine (LPTSTR cmd
)
712 TCHAR szMsg
[RC_STRING_MAX_SIZE
];
713 TCHAR cmdline
[CMDLINE_LENGTH
];
715 #ifdef FEATURE_REDIRECTION
716 TCHAR in
[CMDLINE_LENGTH
] = _T("");
717 TCHAR out
[CMDLINE_LENGTH
] = _T("");
718 TCHAR err
[CMDLINE_LENGTH
] = _T("");
719 TCHAR szTempPath
[MAX_PATH
] = _T(".\\");
720 TCHAR szFileName
[2][MAX_PATH
] = {_T(""), _T("")};
721 HANDLE hFile
[2] = {INVALID_HANDLE_VALUE
, INVALID_HANDLE_VALUE
};
727 BOOL bNewBatch
= TRUE
;
731 #endif /* FEATURE_REDIRECTION */
733 _tcscpy (cmdline
, cmd
);
737 DebugPrintf (_T("ParseCommandLine: (\'%s\')\n"), s
);
740 #ifdef FEATURE_ALIASES
741 /* expand all aliases */
742 ExpandAlias (s
, CMDLINE_LENGTH
);
743 #endif /* FEATURE_ALIAS */
745 #ifdef FEATURE_REDIRECTION
746 /* find the temp path to store temporary files */
747 Length
= GetTempPath (MAX_PATH
, szTempPath
);
748 if (Length
> 0 && Length
< MAX_PATH
)
750 Attributes
= GetFileAttributes(szTempPath
);
751 if (Attributes
== 0xffffffff ||
752 !(Attributes
& FILE_ATTRIBUTE_DIRECTORY
))
757 if (Length
== 0 || Length
>= MAX_PATH
)
759 _tcscpy(szTempPath
, _T(".\\"));
761 if (szTempPath
[_tcslen (szTempPath
) - 1] != _T('\\'))
762 _tcscat (szTempPath
, _T("\\"));
764 /* get the redirections from the command line */
765 num
= GetRedirection (s
, in
, out
, err
, &nRedirFlags
);
767 /* more efficient, but do we really need to do this? */
768 for (t
= in
; _istspace (*t
); t
++)
772 for (t
= out
; _istspace (*t
); t
++)
776 for (t
= err
; _istspace (*t
); t
++)
780 if(bc
&& !_tcslen (in
) && _tcslen (bc
->In
))
782 if(bc
&& !out
[0] && _tcslen(bc
->Out
))
784 nRedirFlags
|= OUTPUT_APPEND
;
785 _tcscpy(out
, bc
->Out
);
787 if(bc
&& !_tcslen (err
) && _tcslen (bc
->Err
))
789 nRedirFlags
|= ERROR_APPEND
;
790 _tcscpy(err
, bc
->Err
);
793 /* Set up the initial conditions ... */
794 /* preserve STDIN, STDOUT and STDERR handles */
795 hOldConIn
= GetStdHandle (STD_INPUT_HANDLE
);
796 hOldConOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
797 hOldConErr
= GetStdHandle (STD_ERROR_HANDLE
);
803 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
805 /* we need make sure the LastError msg is zero before calling CreateFile */
808 /* Set up pipe for the standard input handler */
809 hFile
= CreateFile (in
, GENERIC_READ
, FILE_SHARE_READ
, &sa
, OPEN_EXISTING
,
810 FILE_ATTRIBUTE_NORMAL
, NULL
);
811 if (hFile
== INVALID_HANDLE_VALUE
)
813 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR1
, szMsg
, RC_STRING_MAX_SIZE
);
814 ConErrPrintf(szMsg
, in
);
818 if (!SetStdHandle (STD_INPUT_HANDLE
, hFile
))
820 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR1
, szMsg
, RC_STRING_MAX_SIZE
);
821 ConErrPrintf(szMsg
, in
);
825 DebugPrintf (_T("Input redirected from: %s\n"), in
);
829 /* Now do all but the last pipe command */
830 *szFileName
[0] = _T('\0');
831 hFile
[0] = INVALID_HANDLE_VALUE
;
835 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
837 /* Create unique temporary file name */
838 GetTempFileName (szTempPath
, _T("CMD"), 0, szFileName
[1]);
840 /* we need make sure the LastError msg is zero before calling CreateFile */
843 /* Set current stdout to temporary file */
844 hFile
[1] = CreateFile (szFileName
[1], GENERIC_WRITE
, 0, &sa
,
845 TRUNCATE_EXISTING
, FILE_ATTRIBUTE_TEMPORARY
, NULL
);
847 if (hFile
[1] == INVALID_HANDLE_VALUE
)
849 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR2
, szMsg
, RC_STRING_MAX_SIZE
);
854 SetStdHandle (STD_OUTPUT_HANDLE
, hFile
[1]);
858 /* close stdout file */
859 SetStdHandle (STD_OUTPUT_HANDLE
, hOldConOut
);
860 if ((hFile
[1] != INVALID_HANDLE_VALUE
) && (hFile
[1] != hOldConOut
))
862 CloseHandle (hFile
[1]);
863 hFile
[1] = INVALID_HANDLE_VALUE
;
866 /* close old stdin file */
867 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
868 if ((hFile
[0] != INVALID_HANDLE_VALUE
) && (hFile
[0] != hOldConIn
))
870 /* delete old stdin file, if it is a real file */
871 CloseHandle (hFile
[0]);
872 hFile
[0] = INVALID_HANDLE_VALUE
;
873 DeleteFile (szFileName
[0]);
874 *szFileName
[0] = _T('\0');
877 /* copy stdout file name to stdin file name */
878 _tcscpy (szFileName
[0], szFileName
[1]);
879 *szFileName
[1] = _T('\0');
881 /* we need make sure the LastError msg is zero before calling CreateFile */
884 /* open new stdin file */
885 hFile
[0] = CreateFile (szFileName
[0], GENERIC_READ
, 0, &sa
,
886 OPEN_EXISTING
, FILE_ATTRIBUTE_TEMPORARY
, NULL
);
887 SetStdHandle (STD_INPUT_HANDLE
, hFile
[0]);
889 s
= s
+ _tcslen (s
) + 1;
892 /* Now set up the end conditions... */
893 /* redirect STDOUT */
896 /* Final output to here */
898 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
900 /* we need make sure the LastError msg is zero before calling CreateFile */
903 hFile
= CreateFile (out
, GENERIC_WRITE
, FILE_SHARE_WRITE
| FILE_SHARE_READ
| FILE_SHARE_DELETE
, &sa
,
904 (nRedirFlags
& OUTPUT_APPEND
) ? OPEN_ALWAYS
: CREATE_ALWAYS
,
905 FILE_ATTRIBUTE_NORMAL
| FILE_FLAG_WRITE_THROUGH
, NULL
);
907 if (hFile
== INVALID_HANDLE_VALUE
)
909 INT size
= _tcslen(out
)-1;
911 if (out
[size
] != _T(':'))
913 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR3
, szMsg
, RC_STRING_MAX_SIZE
);
914 ConErrPrintf(szMsg
, out
);
919 hFile
= CreateFile (out
, GENERIC_WRITE
, FILE_SHARE_WRITE
| FILE_SHARE_READ
| FILE_SHARE_DELETE
, &sa
,
920 (nRedirFlags
& OUTPUT_APPEND
) ? OPEN_ALWAYS
: CREATE_ALWAYS
,
921 FILE_ATTRIBUTE_NORMAL
| FILE_FLAG_WRITE_THROUGH
, NULL
);
923 if (hFile
== INVALID_HANDLE_VALUE
)
925 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR3
, szMsg
, RC_STRING_MAX_SIZE
);
926 ConErrPrintf(szMsg
, out
);
932 if (!SetStdHandle (STD_OUTPUT_HANDLE
, hFile
))
934 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR3
, szMsg
, RC_STRING_MAX_SIZE
);
935 ConErrPrintf(szMsg
, out
);
939 if (nRedirFlags
& OUTPUT_APPEND
)
943 if (GetFileType (hFile
) == FILE_TYPE_DISK
)
944 SetFilePointer (hFile
, 0, &lHighPos
, FILE_END
);
947 DebugPrintf (_T("Output redirected to: %s\n"), out
);
950 else if (hOldConOut
!= INVALID_HANDLE_VALUE
)
952 /* Restore original stdout */
953 HANDLE hOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
954 SetStdHandle (STD_OUTPUT_HANDLE
, hOldConOut
);
955 if (hOldConOut
!= hOut
)
957 hOldConOut
= INVALID_HANDLE_VALUE
;
960 /* redirect STDERR */
963 /* Final output to here */
965 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
967 if (!_tcscmp (err
, out
))
970 DebugPrintf (_T("Stdout and stderr will use the same file!!\n"));
972 DuplicateHandle (GetCurrentProcess (),
973 GetStdHandle (STD_OUTPUT_HANDLE
),
974 GetCurrentProcess (),
975 &hFile
, 0, TRUE
, DUPLICATE_SAME_ACCESS
);
979 hFile
= CreateFile (err
,
981 FILE_SHARE_WRITE
| FILE_SHARE_READ
| FILE_SHARE_DELETE
,
983 (nRedirFlags
& ERROR_APPEND
) ? OPEN_ALWAYS
: CREATE_ALWAYS
,
984 FILE_ATTRIBUTE_NORMAL
| FILE_FLAG_WRITE_THROUGH
,
986 if (hFile
== INVALID_HANDLE_VALUE
)
988 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR3
, szMsg
, RC_STRING_MAX_SIZE
);
989 ConErrPrintf(szMsg
, err
);
994 if (!SetStdHandle (STD_ERROR_HANDLE
, hFile
))
996 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR3
, szMsg
, RC_STRING_MAX_SIZE
);
997 ConErrPrintf(szMsg
, err
);
1001 if (nRedirFlags
& ERROR_APPEND
)
1005 if (GetFileType (hFile
) == FILE_TYPE_DISK
)
1006 SetFilePointer (hFile
, 0, &lHighPos
, FILE_END
);
1009 DebugPrintf (_T("Error redirected to: %s\n"), err
);
1012 else if (hOldConErr
!= INVALID_HANDLE_VALUE
)
1014 /* Restore original stderr */
1015 HANDLE hErr
= GetStdHandle (STD_ERROR_HANDLE
);
1016 SetStdHandle (STD_ERROR_HANDLE
, hOldConErr
);
1017 if (hOldConErr
!= hErr
)
1019 hOldConErr
= INVALID_HANDLE_VALUE
;
1026 /* process final command */
1029 #ifdef FEATURE_REDIRECTION
1031 AddBatchRedirection(in
, out
, err
);
1032 /* close old stdin file */
1033 #if 0 /* buggy implementation */
1034 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
1035 if ((hFile
[0] != INVALID_HANDLE_VALUE
) &&
1036 (hFile
[0] != hOldConIn
))
1038 /* delete old stdin file, if it is a real file */
1039 CloseHandle (hFile
[0]);
1040 hFile
[0] = INVALID_HANDLE_VALUE
;
1041 DeleteFile (szFileName
[0]);
1042 *szFileName
[0] = _T('\0');
1045 /* Restore original STDIN */
1046 if (hOldConIn
!= INVALID_HANDLE_VALUE
)
1048 HANDLE hIn
= GetStdHandle (STD_INPUT_HANDLE
);
1049 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
1050 if (hOldConIn
!= hIn
)
1052 hOldConIn
= INVALID_HANDLE_VALUE
;
1057 DebugPrintf (_T("Can't restore STDIN! Is invalid!!\n"), out
);
1060 #endif /* buggy implementation */
1063 if (hOldConIn
!= INVALID_HANDLE_VALUE
)
1065 HANDLE hIn
= GetStdHandle (STD_INPUT_HANDLE
);
1066 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
1067 if (hIn
== INVALID_HANDLE_VALUE
)
1070 DebugPrintf (_T("Previous STDIN is invalid!!\n"));
1075 if (GetFileType (hIn
) == FILE_TYPE_DISK
)
1077 if (hFile
[0] == hIn
)
1079 CloseHandle (hFile
[0]);
1080 hFile
[0] = INVALID_HANDLE_VALUE
;
1081 DeleteFile (szFileName
[0]);
1082 *szFileName
[0] = _T('\0');
1087 DebugPrintf (_T("hFile[0] and hIn dont match!!!\n"));
1095 /* Restore original STDOUT */
1096 if (hOldConOut
!= INVALID_HANDLE_VALUE
)
1098 HANDLE hOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
1099 SetStdHandle (STD_OUTPUT_HANDLE
, hOldConOut
);
1100 if (hOldConOut
!= hOut
)
1102 hOldConOut
= INVALID_HANDLE_VALUE
;
1105 /* Restore original STDERR */
1106 if (hOldConErr
!= INVALID_HANDLE_VALUE
)
1108 HANDLE hErr
= GetStdHandle (STD_ERROR_HANDLE
);
1109 SetStdHandle (STD_ERROR_HANDLE
, hOldConErr
);
1110 if (hOldConErr
!= hErr
)
1112 hOldConErr
= INVALID_HANDLE_VALUE
;
1114 #endif /* FEATURE_REDIRECTION */
1118 GrowIfNecessary_dbg ( UINT needed
, LPTSTR
* ret
, UINT
* retlen
, const char *file
, int line
)
1120 if ( *ret
&& needed
< *retlen
)
1126 *ret
= (LPTSTR
)cmd_alloc_dbg ( *retlen
* sizeof(TCHAR
), file
, line
);
1128 *ret
= (LPTSTR
)cmd_alloc ( *retlen
* sizeof(TCHAR
) );
1131 SetLastError ( ERROR_OUTOFMEMORY
);
1132 return *ret
!= NULL
;
1134 #define GrowIfNecessary(x, y, z) GrowIfNecessary_dbg(x, y, z, __FILE__, __LINE__)
1137 GetEnvVarOrSpecial ( LPCTSTR varName
)
1139 static LPTSTR ret
= NULL
;
1140 static UINT retlen
= 0;
1142 TCHAR varNameFixed
[MAX_PATH
];
1143 TCHAR ReturnValue
[MAX_PATH
];
1147 INT StringPart
[1] = {0};
1149 position
= _tcsstr(varName
, _T(":~"));
1151 _tcsncpy(varNameFixed
, varName
, (int) (position
- varName
));
1153 _tcscpy(varNameFixed
, varName
);
1155 size
= GetEnvironmentVariable ( varNameFixed
, ret
, retlen
);
1156 if ( size
> retlen
)
1158 if ( !GrowIfNecessary ( size
, &ret
, &retlen
) )
1160 size
= GetEnvironmentVariable ( varNameFixed
, ret
, retlen
);
1167 if (_tcschr(position
, _T(',')) != NULL
)
1169 Token
= _tcstok(position
, _T(","));
1170 while ((Token
!= NULL
) && (i
< 2))
1172 StringPart
[i
] = _ttoi(Token
);
1174 Token
= _tcstok (NULL
, _T(","));
1178 if (StringPart
[1] < 0)
1179 StringPart
[1] = _tcslen(ret
+ StringPart
[0]) + StringPart
[1];
1180 _tcsncpy(ReturnValue
, ret
+ StringPart
[0], StringPart
[1]);
1181 _tcscpy(ret
, ReturnValue
);
1190 /* env var doesn't exist, look for a "special" one */
1192 if (_tcsicmp(varNameFixed
,_T("cd")) ==0)
1194 size
= GetCurrentDirectory ( retlen
, ret
);
1195 if ( size
> retlen
)
1197 if ( !GrowIfNecessary ( size
, &ret
, &retlen
) )
1199 size
= GetCurrentDirectory ( retlen
, ret
);
1206 else if (_tcsicmp(varNameFixed
,_T("time")) ==0)
1209 if ( !GrowIfNecessary ( MAX_PATH
, &ret
, &retlen
) )
1212 _sntprintf ( ret
, retlen
, _T("%02d%c%02d%c%02d%c%02d"),
1213 t
.wHour
, cTimeSeparator
, t
.wMinute
, cTimeSeparator
,
1214 t
.wSecond
, cDecimalSeparator
, t
.wMilliseconds
/ 10);
1218 else if (_tcsicmp(varNameFixed
,_T("date")) ==0)
1221 if ( !GrowIfNecessary ( GetDateFormat(LOCALE_USER_DEFAULT
, DATE_SHORTDATE
, NULL
, NULL
, NULL
, 0), &ret
, &retlen
) )
1224 size
= GetDateFormat(LOCALE_USER_DEFAULT
, DATE_SHORTDATE
, NULL
, NULL
, ret
, retlen
);
1232 else if (_tcsicmp(varNameFixed
,_T("random")) ==0)
1234 if ( !GrowIfNecessary ( MAX_PATH
, &ret
, &retlen
) )
1236 /* Get random number */
1237 _itot(rand(),ret
,10);
1242 else if (_tcsicmp(varNameFixed
,_T("cmdcmdline")) ==0)
1244 return GetCommandLine();
1247 /* %CMDEXTVERSION% */
1248 else if (_tcsicmp(varNameFixed
,_T("cmdextversion")) ==0)
1250 if ( !GrowIfNecessary ( MAX_PATH
, &ret
, &retlen
) )
1252 /* Set version number to 2 */
1258 else if (_tcsicmp(varNameFixed
,_T("errorlevel")) ==0)
1260 if ( !GrowIfNecessary ( MAX_PATH
, &ret
, &retlen
) )
1262 _itot(nErrorLevel
,ret
,10);
1266 GrowIfNecessary(_tcslen(varNameFixed
) + 3, &ret
, &retlen
);
1267 _stprintf(ret
,_T("%%%s%%"),varNameFixed
);
1268 return ret
; /* not found - return orginal string */
1272 GetParsedEnvVar ( LPCTSTR varName
, UINT
* varNameLen
, BOOL ModeSetA
)
1274 static LPTSTR ret
= NULL
;
1275 static UINT retlen
= 0;
1285 if ( (*varName
!= '!') && (*varName
++ != '%') )
1295 if (_tcsncicmp(varName
, _T("dp0"), 3) == 0)
1299 return bc
->BatchFilePath
;
1311 if ((tmp
= FindArg (*varName
- _T('0'))))
1317 if ( !GrowIfNecessary ( _tcslen(tmp
)+1, &ret
, &retlen
) )
1319 _tcscpy ( ret
, tmp
);
1322 if ( !GrowIfNecessary ( 3, &ret
, &retlen
) )
1335 // No batch file to see here, move along
1337 if ( !GrowIfNecessary ( 3, &ret
, &retlen
) )
1348 // Copy over the raw params(not including the batch file name
1350 if ( !GrowIfNecessary ( _tcslen(bc
->raw_params
)+1, &ret
, &retlen
) )
1354 _tcscpy ( ret
, bc
->raw_params
);
1358 if ( !GrowIfNecessary ( 2, &ret
, &retlen
) )
1367 /* TODO FIXME 10 is only max size for 32-bit */
1368 if ( !GrowIfNecessary ( 11, &ret
, &retlen
) )
1370 _sntprintf ( ret
, retlen
, _T("%u"), nErrorLevel
);
1378 /* HACK for set/a */
1379 if ( !GrowIfNecessary ( 2, &ret
, &retlen
) )
1387 p
= _tcschr ( varName
, c
);
1390 SetLastError ( ERROR_INVALID_PARAMETER
);
1395 *varNameLen
= size
+ 2;
1396 p
= alloca ( (size
+1) * sizeof(TCHAR
) );
1397 memmove ( p
, varName
, size
* sizeof(TCHAR
) );
1400 return GetEnvVarOrSpecial ( varName
);
1405 * do the prompt/input/process loop
1410 ProcessInput (BOOL bFlag
)
1412 TCHAR commandline
[CMDLINE_LENGTH
];
1413 TCHAR readline
[CMDLINE_LENGTH
];
1423 /* if no batch input then... */
1424 if (!(ip
= ReadBatchLine (&bEchoThisLine
)))
1429 ReadCommand (readline
, CMDLINE_LENGTH
);
1431 bEchoThisLine
= FALSE
;
1439 /* skip leading blanks */
1440 while ( _istspace(*ip
) )
1447 if ( (*ip
== _T('%')) || (*ip
== _T('!')) )
1450 LPCTSTR envVal
= GetParsedEnvVar ( ip
, &envNameLen
, bModeSetA
);
1454 cp
= _stpcpy ( cp
, envVal
);
1458 if (*ip
!= _T('\0') && (_istcntrl (*ip
)))
1462 /* HACK HACK HACK check whether bModeSetA needs to be toggled */
1465 tmp
+= _tcsspn(tmp
,_T(" \t"));
1466 /* first we find and skip and pre-redirections... */
1468 ( _tcschr(_T("<>"),*tmp
)
1469 || !_tcsncmp(tmp
,_T("1>"),2)
1470 || !_tcsncmp(tmp
,_T("2>"),2) ))
1472 if ( _istdigit(*tmp
) )
1476 tmp
+= _tcsspn(tmp
,_T(" \t"));
1477 if ( *tmp
== _T('\"') )
1479 tmp
= _tcschr(tmp
+1,_T('\"'));
1484 tmp
= _tcspbrk(tmp
,_T(" \t"));
1486 tmp
+= _tcsspn(tmp
,_T(" \t"));
1488 /* we should now be pointing to the actual command
1489 * (if there is one yet)*/
1492 /* if we're currently substituting ( which is default )
1493 * check to see if we've parsed out a set/a. if so, we
1494 * need to disable substitution until we come across a
1498 /* look for set /a */
1499 if ( !_tcsnicmp(tmp
,_T("set"),3) )
1502 tmp
+= _tcsspn(tmp
,_T(" \t"));
1503 if ( !_tcsnicmp(tmp
,_T("/a"),2) )
1507 /* if we're not currently substituting, it means we're
1508 * already inside a set /a. now we need to look for
1509 * a redirection in order to turn redirection back on */
1512 /* look for redirector of some kind after the command */
1513 while ( (tmp
= _tcspbrk ( tmp
, _T("^<>|") )) )
1515 if ( *tmp
== _T('^') )
1517 if ( _tcschr(_T("<>|&"), *++tmp
) && *tmp
)
1533 /* Echo batch file line */
1537 ConOutPuts (commandline
);
1540 if (!CheckCtrlBreak(BREAK_INPUT
) && *commandline
)
1542 ParseCommandLine (commandline
);
1543 if (bEcho
&& !bIgnoreEcho
&& (!bIsBatch
|| bEchoThisLine
))
1545 bIgnoreEcho
= FALSE
;
1548 while (!bCanExit
|| !bExit
);
1555 * control-break handler.
1557 BOOL WINAPI
BreakHandler (DWORD dwCtrlType
)
1562 static BOOL SelfGenerated
= FALSE
;
1564 if ((dwCtrlType
!= CTRL_C_EVENT
) &&
1565 (dwCtrlType
!= CTRL_BREAK_EVENT
))
1573 SelfGenerated
= FALSE
;
1578 if (bChildProcessRunning
== TRUE
)
1580 SelfGenerated
= TRUE
;
1581 GenerateConsoleCtrlEvent (dwCtrlType
, 0);
1586 rec
.EventType
= KEY_EVENT
;
1587 rec
.Event
.KeyEvent
.bKeyDown
= TRUE
;
1588 rec
.Event
.KeyEvent
.wRepeatCount
= 1;
1589 rec
.Event
.KeyEvent
.wVirtualKeyCode
= _T('C');
1590 rec
.Event
.KeyEvent
.wVirtualScanCode
= _T('C') - 35;
1591 rec
.Event
.KeyEvent
.uChar
.AsciiChar
= _T('C');
1592 rec
.Event
.KeyEvent
.uChar
.UnicodeChar
= _T('C');
1593 rec
.Event
.KeyEvent
.dwControlKeyState
= RIGHT_CTRL_PRESSED
;
1602 /* FIXME: Handle batch files */
1604 //ConOutPrintf(_T("^C"));
1611 VOID
AddBreakHandler (VOID
)
1613 SetConsoleCtrlHandler ((PHANDLER_ROUTINE
)BreakHandler
, TRUE
);
1617 VOID
RemoveBreakHandler (VOID
)
1619 SetConsoleCtrlHandler ((PHANDLER_ROUTINE
)BreakHandler
, FALSE
);
1624 * show commands and options that are available.
1631 /* print command list */
1632 ConOutResPuts(STRING_CMD_HELP1
);
1635 /* print feature list */
1636 ConOutResPuts(STRING_CMD_HELP2
);
1638 #ifdef FEATURE_ALIASES
1639 ConOutResPuts(STRING_CMD_HELP3
);
1641 #ifdef FEATURE_HISTORY
1642 ConOutResPuts(STRING_CMD_HELP4
);
1644 #ifdef FEATURE_UNIX_FILENAME_COMPLETION
1645 ConOutResPuts(STRING_CMD_HELP5
);
1647 #ifdef FEATURE_DIRECTORY_STACK
1648 ConOutResPuts(STRING_CMD_HELP6
);
1650 #ifdef FEATURE_REDIRECTION
1651 ConOutResPuts(STRING_CMD_HELP7
);
1653 ConOutChar(_T('\n'));
1658 ExecuteAutoRunFile (VOID
)
1660 TCHAR autorun
[MAX_PATH
];
1661 DWORD len
= MAX_PATH
;
1664 if( RegOpenKeyEx(HKEY_LOCAL_MACHINE
,
1665 _T("SOFTWARE\\Microsoft\\Command Processor"),
1668 &hkey
) == ERROR_SUCCESS
)
1670 if(RegQueryValueEx(hkey
,
1675 &len
) == ERROR_SUCCESS
)
1677 ParseCommandLine (autorun
);
1685 * set up global initializations and process parameters
1687 * argc - number of parameters to command.com
1688 * argv - command-line parameters
1692 Initialize (int argc
, const TCHAR
* argv
[])
1694 TCHAR commandline
[CMDLINE_LENGTH
];
1695 TCHAR ModuleName
[_MAX_PATH
+ 1];
1700 //TCHAR *ptr, *cmdLine;
1702 /* get version information */
1703 osvi
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
1704 GetVersionEx (&osvi
);
1706 /* Some people like to run ReactOS cmd.exe on Win98, it helps in the
1707 * build process. So don't link implicitly against ntdll.dll, load it
1708 * dynamically instead */
1710 if (osvi
.dwPlatformId
== VER_PLATFORM_WIN32_NT
)
1712 /* ntdll is always present on NT */
1713 NtDllModule
= GetModuleHandle(TEXT("ntdll.dll"));
1717 /* not all 9x versions have a ntdll.dll, try to load it */
1718 NtDllModule
= LoadLibrary(TEXT("ntdll.dll"));
1721 if (NtDllModule
!= NULL
)
1723 NtQueryInformationProcessPtr
= (NtQueryInformationProcessProc
)GetProcAddress(NtDllModule
, "NtQueryInformationProcess");
1724 NtReadVirtualMemoryPtr
= (NtReadVirtualMemoryProc
)GetProcAddress(NtDllModule
, "NtReadVirtualMemory");
1729 DebugPrintf (_T("[command args:\n"));
1730 for (i
= 0; i
< argc
; i
++)
1732 DebugPrintf (_T("%d. %s\n"), i
, argv
[i
]);
1734 DebugPrintf (_T("]\n"));
1739 /* get default input and output console handles */
1740 hOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
1741 hIn
= GetStdHandle (STD_INPUT_HANDLE
);
1743 /* Set EnvironmentVariable PROMPT if it does not exists any env value.
1744 for you can change the EnvirommentVariable for prompt before cmd start
1745 this patch are not 100% right, if it does not exists a PROMPT value cmd should use
1746 $P$G as defualt not set EnvirommentVariable PROMPT to $P$G if it does not exists */
1747 if (GetEnvironmentVariable(_T("PROMPT"),lpBuffer
, sizeof(lpBuffer
) / sizeof(lpBuffer
[0])) == 0)
1748 SetEnvironmentVariable (_T("PROMPT"), _T("$P$G"));
1751 if (argc
>= 2 && !_tcsncmp (argv
[1], _T("/?"), 2))
1753 ConOutResPaging(TRUE
,STRING_CMD_HELP8
);
1756 SetConsoleMode (hIn
, ENABLE_PROCESSED_INPUT
);
1758 #ifdef INCLUDE_CMD_CHDIR
1764 for (i
= 1; i
< argc
; i
++)
1766 if (!_tcsicmp (argv
[i
], _T("/p")))
1768 if (!IsExistingFile (_T("\\autoexec.bat")))
1770 #ifdef INCLUDE_CMD_DATE
1771 cmd_date (_T(""), _T(""));
1773 #ifdef INCLUDE_CMD_TIME
1774 cmd_time (_T(""), _T(""));
1779 ParseCommandLine (_T("\\autoexec.bat"));
1783 else if (!_tcsicmp (argv
[i
], _T("/c")))
1785 /* This just runs a program and exits */
1789 _tcscpy (commandline
, argv
[i
]);
1792 _tcscat (commandline
, _T(" "));
1793 _tcscat (commandline
, argv
[i
]);
1796 ParseCommandLine(commandline
);
1797 cmd_exit (ProcessInput (TRUE
));
1804 else if (!_tcsicmp (argv
[i
], _T("/k")))
1806 /* This just runs a program and remains */
1810 _tcscpy (commandline
, _T("\""));
1811 _tcscat (commandline
, argv
[i
]);
1812 _tcscat (commandline
, _T("\""));
1815 _tcscat (commandline
, _T(" "));
1816 _tcscat (commandline
, argv
[i
]);
1818 ParseCommandLine(commandline
);
1821 #ifdef INCLUDE_CMD_COLOR
1822 else if (!_tcsnicmp (argv
[i
], _T("/t:"), 3))
1824 /* process /t (color) argument */
1825 wDefColor
= (WORD
)_tcstoul (&argv
[i
][3], NULL
, 16);
1827 SetScreenColor (wColor
, TRUE
);
1834 /* Display a simple version string */
1835 ConOutPrintf(_T("ReactOS Operating System [Version %s-%s]\n"),
1836 _T(KERNEL_RELEASE_STR
),
1837 _T(KERNEL_VERSION_BUILD_STR
));
1839 ConOutPuts (_T("(C) Copyright 1998-") _T(COPYRIGHT_YEAR
) _T(" ReactOS Team.\n"));
1842 ExecuteAutoRunFile ();
1844 #ifdef FEATURE_DIR_STACK
1845 /* initialize directory stack */
1846 InitDirectoryStack ();
1850 #ifdef FEATURE_HISTORY
1851 /*initialize history*/
1855 /* Set COMSPEC environment variable */
1856 if (0 != GetModuleFileName (NULL
, ModuleName
, _MAX_PATH
+ 1))
1858 ModuleName
[_MAX_PATH
] = _T('\0');
1859 SetEnvironmentVariable (_T("COMSPEC"), ModuleName
);
1862 /* add ctrl break handler */
1867 static VOID
Cleanup (int argc
, const TCHAR
*argv
[])
1869 /* run cmdexit.bat */
1870 if (IsExistingFile (_T("cmdexit.bat")))
1872 ConErrResPuts(STRING_CMD_ERROR5
);
1874 ParseCommandLine (_T("cmdexit.bat"));
1876 else if (IsExistingFile (_T("\\cmdexit.bat")))
1878 ConErrResPuts (STRING_CMD_ERROR5
);
1879 ParseCommandLine (_T("\\cmdexit.bat"));
1882 #ifdef FEATURE_DIECTORY_STACK
1883 /* destroy directory stack */
1884 DestroyDirectoryStack ();
1887 #ifdef INCLUDE_CMD_CHDIR
1891 #ifdef FEATURE_HISTORY
1896 /* remove ctrl break handler */
1897 RemoveBreakHandler ();
1898 SetConsoleMode( GetStdHandle( STD_INPUT_HANDLE
),
1899 ENABLE_LINE_INPUT
| ENABLE_PROCESSED_INPUT
| ENABLE_ECHO_INPUT
);
1901 if (NtDllModule
!= NULL
)
1903 FreeLibrary(NtDllModule
);
1910 int cmd_main (int argc
, const TCHAR
*argv
[])
1912 TCHAR startPath
[MAX_PATH
];
1913 CONSOLE_SCREEN_BUFFER_INFO Info
;
1916 GetCurrentDirectory(MAX_PATH
,startPath
);
1923 hConsole
= CreateFile(_T("CONOUT$"), GENERIC_READ
|GENERIC_WRITE
,
1924 FILE_SHARE_READ
|FILE_SHARE_WRITE
, NULL
,
1925 OPEN_EXISTING
, 0, NULL
);
1926 if (GetConsoleScreenBufferInfo(hConsole
, &Info
) == FALSE
)
1928 ConErrFormatMessage(GetLastError());
1931 wColor
= Info
.wAttributes
;
1934 InputCodePage
= GetConsoleCP();
1935 OutputCodePage
= GetConsoleOutputCP();
1936 CMD_ModuleHandle
= GetModuleHandle(NULL
);
1938 /* check switches on command-line */
1939 Initialize(argc
, argv
);
1941 /* call prompt routine */
1942 nExitCode
= ProcessInput(FALSE
);
1944 /* do the cleanup */
1945 Cleanup(argc
, argv
);
1947 cmd_exit(nExitCode
);