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 <ekohl@abo.rhein-zeitung.de>)
88 * First ReactOS release.
89 * Extended length of commandline buffers to 512.
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.
95 * 07-Jan-1999 (Eric Kohl <ekohl@abo.rhein-zeitung.de>)
96 * Added help text ("cmd /?").
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.
104 * 27-Jan-1999 (Eric Kohl <ekohl@abo.rhein-zeitung.de>)
105 * Replaced spawnl() by CreateProcess().
107 * 22-Oct-1999 (Eric Kohl <ekohl@abo.rhein-zeitung.de>)
108 * Added break handler.
110 * 15-Dec-1999 (Eric Kohl <ekohl@abo.rhein-zeitung.de>)
111 * Fixed current directory
113 * 28-Dec-1999 (Eric Kohl <ekohl@abo.rhein-zeitung.de>)
114 * Restore window title after program/batch execution
116 * 03-Feb-2001 (Eric Kohl <ekohl@rz-online.de>)
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.
125 * 28-Mai-2004 (Hartmut Birr)
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
137 #include "resource.h"
140 #define NT_SUCCESS(StatCode) ((NTSTATUS)(StatCode) >= 0)
143 typedef NTSTATUS (STDCALL
*NtQueryInformationProcessProc
)(HANDLE
, PROCESSINFOCLASS
,
144 PVOID
, ULONG
, PULONG
);
145 typedef NTSTATUS (STDCALL
*NtReadVirtualMemoryProc
)(HANDLE
, PVOID
, PVOID
, ULONG
, PULONG
);
147 BOOL bExit
= FALSE
; /* indicates EXIT was typed */
148 BOOL bCanExit
= TRUE
; /* indicates if this shell is exitable */
149 BOOL bCtrlBreak
= FALSE
; /* Ctrl-Break or Ctrl-C hit */
150 BOOL bIgnoreEcho
= FALSE
; /* Ignore 'newline' before 'cls' */
151 INT nErrorLevel
= 0; /* Errorlevel of last launched external program */
152 BOOL bChildProcessRunning
= FALSE
;
153 DWORD dwChildProcessId
= 0;
158 HANDLE CMD_ModuleHandle
;
160 static NtQueryInformationProcessProc NtQueryInformationProcessPtr
;
161 static NtReadVirtualMemoryProc NtReadVirtualMemoryPtr
;
162 static BOOL NtDllChecked
= FALSE
;
164 #ifdef INCLUDE_CMD_COLOR
165 WORD wColor
; /* current color */
166 WORD wDefColor
; /* default color */
170 * is character a delimeter when used on first word?
174 static BOOL
IsDelimiter (TCHAR c
)
176 return (c
== _T('/') || c
== _T('=') || c
== _T('\0') || _istspace (c
));
180 * Is a process a console process?
182 static BOOL
IsConsoleProcess(HANDLE Process
)
185 PROCESS_BASIC_INFORMATION Info
;
190 /* Some people like to run ReactOS cmd.exe on Win98, it helps in the
191 build process. So don't link implicitly against ntdll.dll, load it
192 dynamically instead */
196 NtDllModule
= LoadLibrary(_T("ntdll.dll"));
197 if (NULL
== NtDllModule
)
199 /* Probably non-WinNT system. Just wait for the commands
201 NtQueryInformationProcessPtr
= NULL
;
202 NtReadVirtualMemoryPtr
= NULL
;
205 NtQueryInformationProcessPtr
= (NtQueryInformationProcessProc
)
206 GetProcAddress(NtDllModule
, "NtQueryInformationProcess");
207 NtReadVirtualMemoryPtr
= (NtReadVirtualMemoryProc
)
208 GetProcAddress(NtDllModule
, "NtReadVirtualMemory");
211 if (NULL
== NtQueryInformationProcessPtr
|| NULL
== NtReadVirtualMemoryPtr
)
216 Status
= NtQueryInformationProcessPtr(Process
, ProcessBasicInformation
,
217 &Info
, sizeof(PROCESS_BASIC_INFORMATION
), NULL
);
218 if (! NT_SUCCESS(Status
))
221 DebugPrintf (_T("NtQueryInformationProcess failed with status %08x\n"), Status
);
225 Status
= NtReadVirtualMemoryPtr(Process
, Info
.PebBaseAddress
, &ProcessPeb
,
226 sizeof(PEB
), &BytesRead
);
227 if (! NT_SUCCESS(Status
) || sizeof(PEB
) != BytesRead
)
230 DebugPrintf (_T("Couldn't read virt mem status %08x bytes read %lu\n"), Status
, BytesRead
);
235 return IMAGE_SUBSYSTEM_WINDOWS_CUI
== ProcessPeb
.ImageSubSystem
;
241 #define SHELLEXECUTETEXT "ShellExecuteW"
243 #define SHELLEXECUTETEXT "ShellExecuteA"
246 typedef HINSTANCE (WINAPI
*MYEX
)(
250 LPCTSTR lpParameters
,
257 static BOOL
RunFile(LPTSTR filename
)
264 DebugPrintf (_T("RunFile(%s)\n"), filename
);
266 hShell32
= LoadLibrary(_T("SHELL32.DLL"));
270 DebugPrintf (_T("RunFile: couldn't load SHELL32.DLL!\n"));
275 hShExt
= (MYEX
)(FARPROC
)GetProcAddress(hShell32
, SHELLEXECUTETEXT
);
279 DebugPrintf (_T("RunFile: couldn't find ShellExecuteA/W in SHELL32.DLL!\n"));
281 FreeLibrary(hShell32
);
286 DebugPrintf (_T("RunFile: ShellExecuteA/W is at %x\n"), hShExt
);
289 ret
= (hShExt
)(NULL
, _T("open"), filename
, NULL
, NULL
, SW_SHOWNORMAL
);
292 DebugPrintf (_T("RunFile: ShellExecuteA/W returned %d\n"), (DWORD
)ret
);
295 FreeLibrary(hShell32
);
296 return (((DWORD
)ret
) > 32);
302 * This command (in first) was not found in the command table
304 * first - first word on command line
305 * rest - rest of command line
309 Execute (LPTSTR full
, LPTSTR first
, LPTSTR rest
)
311 TCHAR szFullName
[MAX_PATH
];
313 TCHAR szWindowTitle
[MAX_PATH
];
315 DWORD dwExitCode
= 0;
318 DebugPrintf (_T("Execute: \'%s\' \'%s\'\n"), first
, rest
);
321 /* check for a drive change */
322 if ((_istalpha (first
[0])) && (!_tcscmp (first
+ 1, _T(":"))))
325 if (!SetCurrentDirectory(first
))
326 /* Guess they changed disc or something, handle that gracefully and get to root */
333 working
= SetCurrentDirectory(str
);
336 if (!working
) ConErrResPuts (STRING_FREE_ERROR1
);
341 /* get the PATH environment variable and parse it */
342 /* search the PATH environment variable for the binary */
343 if (!SearchForExecutable (first
, szFullName
))
345 error_bad_command ();
350 GetConsoleTitle (szWindowTitle
, MAX_PATH
);
353 /* check if this is a .BAT or .CMD file */
354 if (!_tcsicmp (_tcsrchr (szFullName
, _T('.')), _T(".bat")) ||
355 !_tcsicmp (_tcsrchr (szFullName
, _T('.')), _T(".cmd")))
358 DebugPrintf (_T("[BATCH: %s %s]\n"), szFullName
, rest
);
360 Batch (szFullName
, first
, rest
);
364 /* exec the program */
365 PROCESS_INFORMATION prci
;
369 DebugPrintf (_T("[EXEC: %s %s]\n"), full
, rest
);
371 /* build command line for CreateProcess() */
373 /* fill startup info */
374 memset (&stui
, 0, sizeof (STARTUPINFO
));
375 stui
.cb
= sizeof (STARTUPINFO
);
376 stui
.dwFlags
= STARTF_USESHOWWINDOW
;
377 stui
.wShowWindow
= SW_SHOWDEFAULT
;
379 // return console to standard mode
380 SetConsoleMode (GetStdHandle(STD_INPUT_HANDLE
),
381 ENABLE_LINE_INPUT
| ENABLE_PROCESSED_INPUT
| ENABLE_ECHO_INPUT
);
383 if (CreateProcess (szFullName
,
388 CREATE_NEW_PROCESS_GROUP
,
394 if (IsConsoleProcess(prci
.hProcess
))
396 /* FIXME: Protect this with critical section */
397 bChildProcessRunning
= TRUE
;
398 dwChildProcessId
= prci
.dwProcessId
;
400 WaitForSingleObject (prci
.hProcess
, INFINITE
);
402 /* FIXME: Protect this with critical section */
403 bChildProcessRunning
= FALSE
;
405 GetExitCodeProcess (prci
.hProcess
, &dwExitCode
);
406 nErrorLevel
= (INT
)dwExitCode
;
408 CloseHandle (prci
.hThread
);
409 CloseHandle (prci
.hProcess
);
414 DebugPrintf (_T("[ShellExecute: %s]\n"), full
);
416 // See if we can run this with ShellExecute() ie myfile.xls
420 DebugPrintf (_T("[ShellExecute failed!: %s]\n"), full
);
422 error_bad_command ();
425 // restore console mode
426 SetConsoleMode( GetStdHandle( STD_INPUT_HANDLE
),
427 ENABLE_PROCESSED_INPUT
);
430 /* Get code page if it has been change */
431 InputCodePage
= GetConsoleCP();
432 OutputCodePage
= GetConsoleOutputCP();
434 SetConsoleTitle (szWindowTitle
);
440 * look through the internal commands and determine whether or not this
441 * command is one of them. If it is, call the command. If not, call
442 * execute to run it as an external program.
444 * line - the command line of the program to run
449 DoCommand (LPTSTR line
)
451 TCHAR com
[CMDLINE_LENGTH
]; /* the first word in the command */
454 LPTSTR rest
; /* pointer to the rest of the command line */
459 DebugPrintf (_T("DoCommand: (\'%s\')\n"), line
);
462 /* Skip over initial white space */
463 while (_istspace (*line
))
469 /* Anything to do ? */
472 if (*rest
== _T('"'))
474 /* treat quoted words specially */
478 while(*rest
!= _T('\0') && *rest
!= _T('"'))
479 *cp
++ = _totlower (*rest
++);
480 if (*rest
== _T('"'))
485 while (!IsDelimiter (*rest
))
486 *cp
++ = _totlower (*rest
++);
490 /* Terminate first word */
493 /* commands are limited to MAX_PATH */
494 if(_tcslen(com
) > MAX_PATH
)
500 /* Skip over whitespace to rest of line */
501 while (_istspace (*rest
))
504 /* Scan internal command table */
505 for (cmdptr
= cmds
;; cmdptr
++)
507 /* If end of table execute ext cmd */
508 if (cmdptr
->name
== NULL
)
510 Execute (line
, com
, rest
);
514 if (!_tcscmp (com
, cmdptr
->name
))
516 cmdptr
->func (com
, rest
);
520 /* The following code handles the case of commands like CD which
521 * are recognised even when the command name and parameter are
522 * not space separated.
528 /* Get length of command name */
529 cl
= _tcslen (cmdptr
->name
);
531 if ((cmdptr
->flags
& CMD_SPECIAL
) &&
532 (!_tcsncmp (cmdptr
->name
, com
, cl
)) &&
533 (_tcschr (_T("\\.-"), *(com
+ cl
))))
535 /* OK its one of the specials...*/
537 /* Terminate first word properly */
540 /* Call with new rest */
541 cmdptr
->func (com
, cstart
+ cl
);
550 * process the command line and execute the appropriate functions
551 * full input/output redirection and piping are supported
554 VOID
ParseCommandLine (LPTSTR cmd
)
556 TCHAR szMsg
[RC_STRING_MAX_SIZE
];
557 TCHAR cmdline
[CMDLINE_LENGTH
];
559 #ifdef FEATURE_REDIRECTION
560 TCHAR in
[CMDLINE_LENGTH
] = _T("");
561 TCHAR out
[CMDLINE_LENGTH
] = _T("");
562 TCHAR err
[CMDLINE_LENGTH
] = _T("");
563 TCHAR szTempPath
[MAX_PATH
] = _T(".\\");
564 TCHAR szFileName
[2][MAX_PATH
] = {_T(""), _T("")};
565 HANDLE hFile
[2] = {INVALID_HANDLE_VALUE
, INVALID_HANDLE_VALUE
};
575 #endif /* FEATURE_REDIRECTION */
577 _tcscpy (cmdline
, cmd
);
581 DebugPrintf (_T("ParseCommandLine: (\'%s\')\n"), s
);
584 #ifdef FEATURE_ALIASES
585 /* expand all aliases */
586 ExpandAlias (s
, CMDLINE_LENGTH
);
587 #endif /* FEATURE_ALIAS */
589 #ifdef FEATURE_REDIRECTION
590 /* find the temp path to store temporary files */
591 Length
= GetTempPath (MAX_PATH
, szTempPath
);
592 if (Length
> 0 && Length
< MAX_PATH
)
594 Attributes
= GetFileAttributes(szTempPath
);
595 if (Attributes
== 0xffffffff ||
596 !(Attributes
& FILE_ATTRIBUTE_DIRECTORY
))
601 if (Length
== 0 || Length
>= MAX_PATH
)
603 _tcscpy(szTempPath
, _T(".\\"));
605 if (szTempPath
[_tcslen (szTempPath
) - 1] != _T('\\'))
606 _tcscat (szTempPath
, _T("\\"));
608 /* get the redirections from the command line */
609 num
= GetRedirection (s
, in
, out
, err
, &nRedirFlags
);
611 /* more efficient, but do we really need to do this? */
612 for (t
= in
; _istspace (*t
); t
++)
616 for (t
= out
; _istspace (*t
); t
++)
620 for (t
= err
; _istspace (*t
); t
++)
624 /* Set up the initial conditions ... */
625 /* preserve STDIN, STDOUT and STDERR handles */
626 hOldConIn
= GetStdHandle (STD_INPUT_HANDLE
);
627 hOldConOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
628 hOldConErr
= GetStdHandle (STD_ERROR_HANDLE
);
634 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
636 hFile
= CreateFile (in
, GENERIC_READ
, FILE_SHARE_READ
, &sa
, OPEN_EXISTING
,
637 FILE_ATTRIBUTE_NORMAL
, NULL
);
638 if (hFile
== INVALID_HANDLE_VALUE
)
640 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR1
, szMsg
, RC_STRING_MAX_SIZE
);
641 ConErrPrintf(szMsg
, in
);
645 if (!SetStdHandle (STD_INPUT_HANDLE
, hFile
))
647 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR1
, szMsg
, RC_STRING_MAX_SIZE
);
648 ConErrPrintf(szMsg
, in
);
652 DebugPrintf (_T("Input redirected from: %s\n"), in
);
656 /* Now do all but the last pipe command */
657 *szFileName
[0] = _T('\0');
658 hFile
[0] = INVALID_HANDLE_VALUE
;
662 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
664 /* Create unique temporary file name */
665 GetTempFileName (szTempPath
, _T("CMD"), 0, szFileName
[1]);
667 /* Set current stdout to temporary file */
668 hFile
[1] = CreateFile (szFileName
[1], GENERIC_WRITE
, 0, &sa
,
669 TRUNCATE_EXISTING
, FILE_ATTRIBUTE_TEMPORARY
, NULL
);
670 if (hFile
[1] == INVALID_HANDLE_VALUE
)
672 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR2
, szMsg
, RC_STRING_MAX_SIZE
);
677 SetStdHandle (STD_OUTPUT_HANDLE
, hFile
[1]);
681 /* close stdout file */
682 SetStdHandle (STD_OUTPUT_HANDLE
, hOldConOut
);
683 if ((hFile
[1] != INVALID_HANDLE_VALUE
) && (hFile
[1] != hOldConOut
))
685 CloseHandle (hFile
[1]);
686 hFile
[1] = INVALID_HANDLE_VALUE
;
689 /* close old stdin file */
690 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
691 if ((hFile
[0] != INVALID_HANDLE_VALUE
) && (hFile
[0] != hOldConIn
))
693 /* delete old stdin file, if it is a real file */
694 CloseHandle (hFile
[0]);
695 hFile
[0] = INVALID_HANDLE_VALUE
;
696 DeleteFile (szFileName
[0]);
697 *szFileName
[0] = _T('\0');
700 /* copy stdout file name to stdin file name */
701 _tcscpy (szFileName
[0], szFileName
[1]);
702 *szFileName
[1] = _T('\0');
704 /* open new stdin file */
705 hFile
[0] = CreateFile (szFileName
[0], GENERIC_READ
, 0, &sa
,
706 OPEN_EXISTING
, FILE_ATTRIBUTE_TEMPORARY
, NULL
);
707 SetStdHandle (STD_INPUT_HANDLE
, hFile
[0]);
709 s
= s
+ _tcslen (s
) + 1;
712 /* Now set up the end conditions... */
713 /* redirect STDOUT */
716 /* Final output to here */
718 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
720 hFile
= CreateFile (out
, GENERIC_WRITE
, FILE_SHARE_READ
, &sa
,
721 (nRedirFlags
& OUTPUT_APPEND
) ? OPEN_ALWAYS
: CREATE_ALWAYS
,
722 FILE_ATTRIBUTE_NORMAL
, NULL
);
723 if (hFile
== INVALID_HANDLE_VALUE
)
725 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR3
, szMsg
, RC_STRING_MAX_SIZE
);
726 ConErrPrintf(szMsg
, out
);
730 if (!SetStdHandle (STD_OUTPUT_HANDLE
, hFile
))
732 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR3
, szMsg
, RC_STRING_MAX_SIZE
);
733 ConErrPrintf(szMsg
, out
);
737 if (nRedirFlags
& OUTPUT_APPEND
)
741 if (GetFileType (hFile
) == FILE_TYPE_DISK
)
742 SetFilePointer (hFile
, 0, &lHighPos
, FILE_END
);
745 DebugPrintf (_T("Output redirected to: %s\n"), out
);
748 else if (hOldConOut
!= INVALID_HANDLE_VALUE
)
750 /* Restore original stdout */
751 HANDLE hOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
752 SetStdHandle (STD_OUTPUT_HANDLE
, hOldConOut
);
753 if (hOldConOut
!= hOut
)
755 hOldConOut
= INVALID_HANDLE_VALUE
;
758 /* redirect STDERR */
761 /* Final output to here */
763 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
765 if (!_tcscmp (err
, out
))
768 DebugPrintf (_T("Stdout and stderr will use the same file!!\n"));
770 DuplicateHandle (GetCurrentProcess (),
771 GetStdHandle (STD_OUTPUT_HANDLE
),
772 GetCurrentProcess (),
773 &hFile
, 0, TRUE
, DUPLICATE_SAME_ACCESS
);
777 hFile
= CreateFile (err
,
781 (nRedirFlags
& ERROR_APPEND
) ? OPEN_ALWAYS
: CREATE_ALWAYS
,
782 FILE_ATTRIBUTE_NORMAL
,
784 if (hFile
== INVALID_HANDLE_VALUE
)
786 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR3
, szMsg
, RC_STRING_MAX_SIZE
);
787 ConErrPrintf(szMsg
, err
);
792 if (!SetStdHandle (STD_ERROR_HANDLE
, hFile
))
794 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR3
, szMsg
, RC_STRING_MAX_SIZE
);
795 ConErrPrintf(szMsg
, err
);
799 if (nRedirFlags
& ERROR_APPEND
)
803 if (GetFileType (hFile
) == FILE_TYPE_DISK
)
804 SetFilePointer (hFile
, 0, &lHighPos
, FILE_END
);
807 DebugPrintf (_T("Error redirected to: %s\n"), err
);
810 else if (hOldConErr
!= INVALID_HANDLE_VALUE
)
812 /* Restore original stderr */
813 HANDLE hErr
= GetStdHandle (STD_ERROR_HANDLE
);
814 SetStdHandle (STD_ERROR_HANDLE
, hOldConErr
);
815 if (hOldConErr
!= hErr
)
817 hOldConErr
= INVALID_HANDLE_VALUE
;
821 /* process final command */
824 #ifdef FEATURE_REDIRECTION
825 /* close old stdin file */
826 #if 0 /* buggy implementation */
827 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
828 if ((hFile
[0] != INVALID_HANDLE_VALUE
) &&
829 (hFile
[0] != hOldConIn
))
831 /* delete old stdin file, if it is a real file */
832 CloseHandle (hFile
[0]);
833 hFile
[0] = INVALID_HANDLE_VALUE
;
834 DeleteFile (szFileName
[0]);
835 *szFileName
[0] = _T('\0');
838 /* Restore original STDIN */
839 if (hOldConIn
!= INVALID_HANDLE_VALUE
)
841 HANDLE hIn
= GetStdHandle (STD_INPUT_HANDLE
);
842 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
843 if (hOldConIn
!= hIn
)
845 hOldConIn
= INVALID_HANDLE_VALUE
;
850 DebugPrintf (_T("Can't restore STDIN! Is invalid!!\n"), out
);
853 #endif /* buggy implementation */
856 if (hOldConIn
!= INVALID_HANDLE_VALUE
)
858 HANDLE hIn
= GetStdHandle (STD_INPUT_HANDLE
);
859 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
860 if (hIn
== INVALID_HANDLE_VALUE
)
863 DebugPrintf (_T("Previous STDIN is invalid!!\n"));
868 if (GetFileType (hIn
) == FILE_TYPE_DISK
)
872 CloseHandle (hFile
[0]);
873 hFile
[0] = INVALID_HANDLE_VALUE
;
874 DeleteFile (szFileName
[0]);
875 *szFileName
[0] = _T('\0');
880 DebugPrintf (_T("hFile[0] and hIn dont match!!!\n"));
888 /* Restore original STDOUT */
889 if (hOldConOut
!= INVALID_HANDLE_VALUE
)
891 HANDLE hOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
892 SetStdHandle (STD_OUTPUT_HANDLE
, hOldConOut
);
893 if (hOldConOut
!= hOut
)
895 hOldConOut
= INVALID_HANDLE_VALUE
;
898 /* Restore original STDERR */
899 if (hOldConErr
!= INVALID_HANDLE_VALUE
)
901 HANDLE hErr
= GetStdHandle (STD_ERROR_HANDLE
);
902 SetStdHandle (STD_ERROR_HANDLE
, hOldConErr
);
903 if (hOldConErr
!= hErr
)
905 hOldConErr
= INVALID_HANDLE_VALUE
;
907 #endif /* FEATURE_REDIRECTION */
912 * do the prompt/input/process loop
917 ProcessInput (BOOL bFlag
)
919 TCHAR commandline
[CMDLINE_LENGTH
];
920 TCHAR readline
[CMDLINE_LENGTH
];
929 /* if no batch input then... */
930 if (!(ip
= ReadBatchLine (&bEchoThisLine
)))
935 ReadCommand (readline
, CMDLINE_LENGTH
);
937 bEchoThisLine
= FALSE
;
961 if ((tp
= FindArg (*ip
- _T('0'))))
963 cp
= _stpcpy (cp
, tp
);
971 cp
+= _stprintf (cp
, _T("%u"), nErrorLevel
);
976 tp
= _tcschr(ip
, _T('%'));
978 (tp
<= _tcschr(ip
, _T(' ')) - 1))
983 /* FIXME: This is just a quick hack!! */
984 /* Do a proper memory allocation!! */
985 if (GetEnvironmentVariable (ip
, evar
, 512))
986 cp
= _stpcpy (cp
, evar
);
1006 /* strip trailing spaces */
1007 while ((--cp
>= commandline
) && _istspace (*cp
));
1009 *(cp
+ 1) = _T('\0');
1012 /* Echo batch file line */
1016 ConOutPuts (commandline
);
1021 ParseCommandLine (commandline
);
1022 if (bEcho
&& !bIgnoreEcho
)
1024 bIgnoreEcho
= FALSE
;
1027 while (!bCanExit
|| !bExit
);
1034 * control-break handler.
1036 BOOL WINAPI
BreakHandler (DWORD dwCtrlType
)
1039 if ((dwCtrlType
!= CTRL_C_EVENT
) &&
1040 (dwCtrlType
!= CTRL_BREAK_EVENT
))
1043 if (bChildProcessRunning
== TRUE
)
1045 GenerateConsoleCtrlEvent (CTRL_C_EVENT
,
1050 /* FIXME: Handle batch files */
1052 /* FIXME: Print "^C" */
1059 VOID
AddBreakHandler (VOID
)
1061 SetConsoleCtrlHandler ((PHANDLER_ROUTINE
)BreakHandler
, TRUE
);
1065 VOID
RemoveBreakHandler (VOID
)
1067 SetConsoleCtrlHandler ((PHANDLER_ROUTINE
)BreakHandler
, FALSE
);
1072 * show commands and options that are available.
1079 /* print command list */
1080 ConOutResPuts(STRING_CMD_HELP1
);
1083 /* print feature list */
1084 ConOutResPuts(STRING_CMD_HELP2
);
1086 #ifdef FEATURE_ALIASES
1087 ConOutResPuts(STRING_CMD_HELP3
);
1089 #ifdef FEATURE_HISTORY
1090 ConOutResPuts(STRING_CMD_HELP4
);
1092 #ifdef FEATURE_UNIX_FILENAME_COMPLETION
1093 ConOutResPuts(STRING_CMD_HELP5
);
1095 #ifdef FEATURE_DIRECTORY_STACK
1096 ConOutResPuts(STRING_CMD_HELP6
);
1098 #ifdef FEATURE_REDIRECTION
1099 ConOutResPuts(STRING_CMD_HELP7
);
1101 ConOutChar(_T('\n'));
1106 * set up global initializations and process parameters
1108 * argc - number of parameters to command.com
1109 * argv - command-line parameters
1113 Initialize (int argc
, TCHAR
* argv
[])
1115 TCHAR commandline
[CMDLINE_LENGTH
];
1116 TCHAR ModuleName
[_MAX_PATH
+ 1];
1120 //TCHAR *ptr, *cmdLine;
1126 DebugPrintf (_T("[command args:\n"));
1127 for (x
= 0; x
< argc
; x
++)
1129 DebugPrintf (_T("%d. %s\n"), x
, argv
[x
]);
1131 DebugPrintf (_T("]\n"));
1134 /* get version information */
1135 osvi
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
1136 GetVersionEx (&osvi
);
1140 /* get default input and output console handles */
1141 hOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
1142 hIn
= GetStdHandle (STD_INPUT_HANDLE
);
1145 if (argc
>= 2 && !_tcsncmp (argv
[1], _T("/?"), 2))
1147 ConOutResPuts(STRING_CMD_HELP8
);
1150 SetConsoleMode (hIn
, ENABLE_PROCESSED_INPUT
);
1152 #ifdef INCLUDE_CMD_CHDIR
1156 #ifdef FATURE_ALIASES
1162 for (i
= 1; i
< argc
; i
++)
1164 if (!_tcsicmp (argv
[i
], _T("/p")))
1166 if (!IsExistingFile (_T("\\autoexec.bat")))
1168 #ifdef INCLUDE_CMD_DATE
1169 cmd_date (_T(""), _T(""));
1171 #ifdef INCLUDE_CMD_TIME
1172 cmd_time (_T(""), _T(""));
1177 ParseCommandLine (_T("\\autoexec.bat"));
1181 else if (!_tcsicmp (argv
[i
], _T("/c")))
1183 /* This just runs a program and exits */
1187 _tcscpy (commandline
, argv
[i
]);
1190 _tcscat (commandline
, _T(" "));
1191 _tcscat (commandline
, argv
[i
]);
1194 ParseCommandLine(commandline
);
1195 ExitProcess (ProcessInput (TRUE
));
1202 else if (!_tcsicmp (argv
[i
], _T("/k")))
1204 /* This just runs a program and remains */
1208 _tcscpy (commandline
, argv
[i
]);
1211 _tcscat (commandline
, _T(" "));
1212 _tcscat (commandline
, argv
[i
]);
1215 ParseCommandLine(commandline
);
1218 #ifdef INCLUDE_CMD_COLOR
1219 else if (!_tcsnicmp (argv
[i
], _T("/t:"), 3))
1221 /* process /t (color) argument */
1222 wDefColor
= (WORD
)_tcstoul (&argv
[i
][3], NULL
, 16);
1224 SetScreenColor (wColor
, TRUE
);
1230 /* run cmdstart.bat */
1231 if (IsExistingFile (_T("cmdstart.bat")))
1233 ParseCommandLine (_T("cmdstart.bat"));
1235 else if (IsExistingFile (_T("\\cmdstart.bat")))
1237 ParseCommandLine (_T("\\cmdstart.bat"));
1242 /* try to run cmdstart.bat from install dir */
1245 _tcscpy (commandline
, argv
[0]);
1246 p
= _tcsrchr (commandline
, _T('\\')) + 1;
1247 _tcscpy (p
, _T("cmdstart.bat"));
1249 if (IsExistingFile (_T("commandline")))
1251 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR4
, szMsg
, RC_STRING_MAX_SIZE
);
1252 ConErrPrintf(szMsg
, commandline
);
1253 ParseCommandLine (commandline
);
1258 #ifdef FEATURE_DIR_STACK
1259 /* initialize directory stack */
1260 InitDirectoryStack ();
1264 #ifdef FEATURE_HISTORY
1265 /*initialize history*/
1269 /* Set COMSPEC environment variable */
1270 if (0 != GetModuleFileName (NULL
, ModuleName
, _MAX_PATH
+ 1))
1272 ModuleName
[_MAX_PATH
] = _T('\0');
1273 SetEnvironmentVariable (_T("COMSPEC"), ModuleName
);
1276 /* add ctrl break handler */
1281 static VOID
Cleanup (int argc
, TCHAR
*argv
[])
1284 TCHAR szMsg
[RC_STRING_MAX_SIZE
];
1287 /* run cmdexit.bat */
1288 if (IsExistingFile (_T("cmdexit.bat")))
1290 ConErrResPuts(STRING_CMD_ERROR5
);
1292 ParseCommandLine (_T("cmdexit.bat"));
1294 else if (IsExistingFile (_T("\\cmdexit.bat")))
1296 ConErrResPuts (STRING_CMD_ERROR5
);
1297 ParseCommandLine (_T("\\cmdexit.bat"));
1302 /* try to run cmdexit.bat from install dir */
1303 TCHAR commandline
[CMDLINE_LENGTH
];
1306 _tcscpy (commandline
, argv
[0]);
1307 p
= _tcsrchr (commandline
, _T('\\')) + 1;
1308 _tcscpy (p
, _T("cmdexit.bat"));
1310 if (IsExistingFile (_T("commandline")))
1312 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR4
, szMsg
, RC_STRING_MAX_SIZE
);
1313 ConErrPrintf(szMsg
, commandline
);
1314 ParseCommandLine (commandline
);
1319 #ifdef FEATURE_ALIASES
1323 #ifdef FEATURE_DIECTORY_STACK
1324 /* destroy directory stack */
1325 DestroyDirectoryStack ();
1328 #ifdef INCLUDE_CMD_CHDIR
1332 #ifdef FEATURE_HISTORY
1337 /* remove ctrl break handler */
1338 RemoveBreakHandler ();
1339 SetConsoleMode( GetStdHandle( STD_INPUT_HANDLE
),
1340 ENABLE_LINE_INPUT
| ENABLE_PROCESSED_INPUT
| ENABLE_ECHO_INPUT
);
1345 PWCHAR
* _CommandLineToArgvW(PWCHAR lpCmdLine
, int *pNumArgs
)
1347 PWCHAR
* argvw
= NULL
;
1348 PWCHAR ptr
= lpCmdLine
;
1355 while(lpCmdLine
&& *lpCmdLine
)
1357 while (iswspace(*lpCmdLine
)) lpCmdLine
++;
1360 if ((NumArgs
% 10)==0)
1362 PWCHAR
* old_argvw
= argvw
;
1363 argvw
= malloc((NumArgs
+ 10) * sizeof(PWCHAR
));
1364 memcpy(argvw
, old_argvw
, NumArgs
* sizeof(PWCHAR
));
1367 ptr
= wcschr(lpCmdLine
, L
' ');
1370 len
= ptr
- lpCmdLine
;
1374 len
= wcslen(lpCmdLine
);
1376 str
= malloc((len
+ 1) * sizeof(WCHAR
));
1377 memcpy(str
, lpCmdLine
, len
* sizeof(WCHAR
));
1384 *pNumArgs
= NumArgs
;
1396 int main (int argc
, char *argv
[])
1399 CONSOLE_SCREEN_BUFFER_INFO Info
;
1405 argv
= _CommandLineToArgvW(GetCommandLineW(), &argc
);
1407 argv
= CommandLineToArgvW(GetCommandLineW(), &argc
);
1415 hConsole
= CreateFile(_T("CONOUT$"), GENERIC_READ
|GENERIC_WRITE
,
1416 FILE_SHARE_READ
|FILE_SHARE_WRITE
, NULL
,
1417 OPEN_EXISTING
, 0, NULL
);
1418 if (GetConsoleScreenBufferInfo(hConsole
, &Info
) == FALSE
)
1420 ConOutFormatMessage(GetLastError());
1423 wColor
= Info
.wAttributes
;
1426 InputCodePage
= GetConsoleCP();
1427 OutputCodePage
= GetConsoleOutputCP();
1428 CMD_ModuleHandle
= GetModuleHandle(NULL
);
1430 /* check switches on command-line */
1431 Initialize(argc
, argv
);
1433 /* call prompt routine */
1434 nExitCode
= ProcessInput(FALSE
);
1436 /* do the cleanup */
1437 Cleanup(argc
, argv
);