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;
159 static NtQueryInformationProcessProc NtQueryInformationProcessPtr
;
160 static NtReadVirtualMemoryProc NtReadVirtualMemoryPtr
;
161 static BOOL NtDllChecked
= FALSE
;
163 #ifdef INCLUDE_CMD_COLOR
164 WORD wColor
; /* current color */
165 WORD wDefColor
; /* default color */
169 * is character a delimeter when used on first word?
173 static BOOL
IsDelimiter (TCHAR c
)
175 return (c
== _T('/') || c
== _T('=') || c
== _T('\0') || _istspace (c
));
179 * Is a process a console process?
181 static BOOL
IsConsoleProcess(HANDLE Process
)
184 PROCESS_BASIC_INFORMATION Info
;
189 /* Some people like to run ReactOS cmd.exe on Win98, it helps in the
190 build process. So don't link implicitly against ntdll.dll, load it
191 dynamically instead */
195 NtDllModule
= LoadLibrary(_T("ntdll.dll"));
196 if (NULL
== NtDllModule
)
198 /* Probably non-WinNT system. Just wait for the commands
200 NtQueryInformationProcessPtr
= NULL
;
201 NtReadVirtualMemoryPtr
= NULL
;
204 NtQueryInformationProcessPtr
= (NtQueryInformationProcessProc
)
205 GetProcAddress(NtDllModule
, "NtQueryInformationProcess");
206 NtReadVirtualMemoryPtr
= (NtReadVirtualMemoryProc
)
207 GetProcAddress(NtDllModule
, "NtReadVirtualMemory");
210 if (NULL
== NtQueryInformationProcessPtr
|| NULL
== NtReadVirtualMemoryPtr
)
215 Status
= NtQueryInformationProcessPtr(Process
, ProcessBasicInformation
,
216 &Info
, sizeof(PROCESS_BASIC_INFORMATION
), NULL
);
217 if (! NT_SUCCESS(Status
))
220 DebugPrintf (_T("NtQueryInformationProcess failed with status %08x\n"), Status
);
224 Status
= NtReadVirtualMemoryPtr(Process
, Info
.PebBaseAddress
, &ProcessPeb
,
225 sizeof(PEB
), &BytesRead
);
226 if (! NT_SUCCESS(Status
) || sizeof(PEB
) != BytesRead
)
229 DebugPrintf (_T("Couldn't read virt mem status %08x bytes read %lu\n"), Status
, BytesRead
);
234 return IMAGE_SUBSYSTEM_WINDOWS_CUI
== ProcessPeb
.ImageSubSystem
;
240 #define SHELLEXECUTETEXT "ShellExecuteW"
242 #define SHELLEXECUTETEXT "ShellExecuteA"
245 typedef HINSTANCE (WINAPI
*MYEX
)(
249 LPCTSTR lpParameters
,
256 static BOOL
RunFile(LPTSTR filename
)
263 DebugPrintf (_T("RunFile(%s)\n"), filename
);
265 hShell32
= LoadLibrary(_T("SHELL32.DLL"));
269 DebugPrintf (_T("RunFile: couldn't load SHELL32.DLL!\n"));
274 hShExt
= (MYEX
)(FARPROC
)GetProcAddress(hShell32
, SHELLEXECUTETEXT
);
278 DebugPrintf (_T("RunFile: couldn't find ShellExecuteA/W in SHELL32.DLL!\n"));
280 FreeLibrary(hShell32
);
285 DebugPrintf (_T("RunFile: ShellExecuteA/W is at %x\n"), hShExt
);
288 ret
= (hShExt
)(NULL
, _T("open"), filename
, NULL
, NULL
, SW_SHOWNORMAL
);
291 DebugPrintf (_T("RunFile: ShellExecuteA/W returned %d\n"), (DWORD
)ret
);
294 FreeLibrary(hShell32
);
295 return (((DWORD
)ret
) > 32);
301 * This command (in first) was not found in the command table
303 * first - first word on command line
304 * rest - rest of command line
308 Execute (LPTSTR full
, LPTSTR first
, LPTSTR rest
)
310 TCHAR szFullName
[MAX_PATH
];
312 TCHAR szWindowTitle
[MAX_PATH
];
314 DWORD dwExitCode
= 0;
317 DebugPrintf (_T("Execute: \'%s\' \'%s\'\n"), first
, rest
);
320 /* check for a drive change */
321 if ((_istalpha (first
[0])) && (!_tcscmp (first
+ 1, _T(":"))))
324 if (!SetCurrentDirectory(first
))
325 /* Guess they changed disc or something, handle that gracefully and get to root */
332 working
= SetCurrentDirectory(str
);
335 if (!working
) ConErrPuts (INVALIDDRIVE
);
340 /* get the PATH environment variable and parse it */
341 /* search the PATH environment variable for the binary */
342 if (!SearchForExecutable (first
, szFullName
))
344 error_bad_command ();
349 GetConsoleTitle (szWindowTitle
, MAX_PATH
);
352 /* check if this is a .BAT or .CMD file */
353 if (!_tcsicmp (_tcsrchr (szFullName
, _T('.')), _T(".bat")) ||
354 !_tcsicmp (_tcsrchr (szFullName
, _T('.')), _T(".cmd")))
357 DebugPrintf (_T("[BATCH: %s %s]\n"), szFullName
, rest
);
359 Batch (szFullName
, first
, rest
);
363 /* exec the program */
364 PROCESS_INFORMATION prci
;
368 DebugPrintf (_T("[EXEC: %s %s]\n"), full
, rest
);
370 /* build command line for CreateProcess() */
372 /* fill startup info */
373 memset (&stui
, 0, sizeof (STARTUPINFO
));
374 stui
.cb
= sizeof (STARTUPINFO
);
375 stui
.dwFlags
= STARTF_USESHOWWINDOW
;
376 stui
.wShowWindow
= SW_SHOWDEFAULT
;
378 // return console to standard mode
379 SetConsoleMode (GetStdHandle(STD_INPUT_HANDLE
),
380 ENABLE_LINE_INPUT
| ENABLE_PROCESSED_INPUT
| ENABLE_ECHO_INPUT
);
382 if (CreateProcess (szFullName
,
387 CREATE_NEW_PROCESS_GROUP
,
393 if (IsConsoleProcess(prci
.hProcess
))
395 /* FIXME: Protect this with critical section */
396 bChildProcessRunning
= TRUE
;
397 dwChildProcessId
= prci
.dwProcessId
;
399 WaitForSingleObject (prci
.hProcess
, INFINITE
);
401 /* FIXME: Protect this with critical section */
402 bChildProcessRunning
= FALSE
;
404 GetExitCodeProcess (prci
.hProcess
, &dwExitCode
);
405 nErrorLevel
= (INT
)dwExitCode
;
407 CloseHandle (prci
.hThread
);
408 CloseHandle (prci
.hProcess
);
413 DebugPrintf (_T("[ShellExecute: %s]\n"), full
);
415 // See if we can run this with ShellExecute() ie myfile.xls
419 DebugPrintf (_T("[ShellExecute failed!: %s]\n"), full
);
421 error_bad_command ();
424 // restore console mode
425 SetConsoleMode( GetStdHandle( STD_INPUT_HANDLE
),
426 ENABLE_PROCESSED_INPUT
);
429 /* Get code page if it has been change */
430 GetCodePage
= GetConsoleCP();
431 OutCodePage
= GetConsoleOutputCP();
433 SetConsoleTitle (szWindowTitle
);
439 * look through the internal commands and determine whether or not this
440 * command is one of them. If it is, call the command. If not, call
441 * execute to run it as an external program.
443 * line - the command line of the program to run
448 DoCommand (LPTSTR line
)
450 TCHAR com
[CMDLINE_LENGTH
]; /* the first word in the command */
453 LPTSTR rest
; /* pointer to the rest of the command line */
458 DebugPrintf (_T("DoCommand: (\'%s\')\n"), line
);
461 /* Skip over initial white space */
462 while (_istspace (*line
))
468 /* Anything to do ? */
471 if (*rest
== _T('"'))
473 /* treat quoted words specially */
477 while(*rest
!= _T('\0') && *rest
!= _T('"'))
478 *cp
++ = _totlower (*rest
++);
479 if (*rest
== _T('"'))
484 while (!IsDelimiter (*rest
))
485 *cp
++ = _totlower (*rest
++);
489 /* Terminate first word */
492 /* commands are limited to MAX_PATH */
493 if(_tcslen(com
) > MAX_PATH
)
499 /* Skip over whitespace to rest of line */
500 while (_istspace (*rest
))
503 /* Scan internal command table */
504 for (cmdptr
= cmds
;; cmdptr
++)
506 /* If end of table execute ext cmd */
507 if (cmdptr
->name
== NULL
)
509 Execute (line
, com
, rest
);
513 if (!_tcscmp (com
, cmdptr
->name
))
515 cmdptr
->func (com
, rest
);
519 /* The following code handles the case of commands like CD which
520 * are recognised even when the command name and parameter are
521 * not space separated.
527 /* Get length of command name */
528 cl
= _tcslen (cmdptr
->name
);
530 if ((cmdptr
->flags
& CMD_SPECIAL
) &&
531 (!_tcsncmp (cmdptr
->name
, com
, cl
)) &&
532 (_tcschr (_T("\\.-"), *(com
+ cl
))))
534 /* OK its one of the specials...*/
536 /* Terminate first word properly */
539 /* Call with new rest */
540 cmdptr
->func (com
, cstart
+ cl
);
549 * process the command line and execute the appropriate functions
550 * full input/output redirection and piping are supported
553 VOID
ParseCommandLine (LPTSTR cmd
)
555 TCHAR szMsg
[RC_STRING_MAX_SIZE
];
556 TCHAR cmdline
[CMDLINE_LENGTH
];
558 #ifdef FEATURE_REDIRECTION
559 TCHAR in
[CMDLINE_LENGTH
] = _T("");
560 TCHAR out
[CMDLINE_LENGTH
] = _T("");
561 TCHAR err
[CMDLINE_LENGTH
] = _T("");
562 TCHAR szTempPath
[MAX_PATH
] = _T(".\\");
563 TCHAR szFileName
[2][MAX_PATH
] = {_T(""), _T("")};
564 HANDLE hFile
[2] = {INVALID_HANDLE_VALUE
, INVALID_HANDLE_VALUE
};
574 #endif /* FEATURE_REDIRECTION */
576 _tcscpy (cmdline
, cmd
);
580 DebugPrintf (_T("ParseCommandLine: (\'%s\')\n"), s
);
583 #ifdef FEATURE_ALIASES
584 /* expand all aliases */
585 ExpandAlias (s
, CMDLINE_LENGTH
);
586 #endif /* FEATURE_ALIAS */
588 #ifdef FEATURE_REDIRECTION
589 /* find the temp path to store temporary files */
590 Length
= GetTempPath (MAX_PATH
, szTempPath
);
591 if (Length
> 0 && Length
< MAX_PATH
)
593 Attributes
= GetFileAttributes(szTempPath
);
594 if (Attributes
== 0xffffffff ||
595 !(Attributes
& FILE_ATTRIBUTE_DIRECTORY
))
600 if (Length
== 0 || Length
>= MAX_PATH
)
602 _tcscpy(szTempPath
, _T(".\\"));
604 if (szTempPath
[_tcslen (szTempPath
) - 1] != _T('\\'))
605 _tcscat (szTempPath
, _T("\\"));
607 /* get the redirections from the command line */
608 num
= GetRedirection (s
, in
, out
, err
, &nRedirFlags
);
610 /* more efficient, but do we really need to do this? */
611 for (t
= in
; _istspace (*t
); t
++)
615 for (t
= out
; _istspace (*t
); t
++)
619 for (t
= err
; _istspace (*t
); t
++)
623 /* Set up the initial conditions ... */
624 /* preserve STDIN, STDOUT and STDERR handles */
625 hOldConIn
= GetStdHandle (STD_INPUT_HANDLE
);
626 hOldConOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
627 hOldConErr
= GetStdHandle (STD_ERROR_HANDLE
);
633 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
635 hFile
= CreateFile (in
, GENERIC_READ
, FILE_SHARE_READ
, &sa
, OPEN_EXISTING
,
636 FILE_ATTRIBUTE_NORMAL
, NULL
);
637 if (hFile
== INVALID_HANDLE_VALUE
)
639 LoadString(GetModuleHandle(NULL
), STRING_CMD_ERROR1
, szMsg
, RC_STRING_MAX_SIZE
);
640 ConErrPrintf(szMsg
, in
);
644 if (!SetStdHandle (STD_INPUT_HANDLE
, hFile
))
646 LoadString(GetModuleHandle(NULL
), STRING_CMD_ERROR1
, szMsg
, RC_STRING_MAX_SIZE
);
647 ConErrPrintf(szMsg
, in
);
651 DebugPrintf (_T("Input redirected from: %s\n"), in
);
655 /* Now do all but the last pipe command */
656 *szFileName
[0] = _T('\0');
657 hFile
[0] = INVALID_HANDLE_VALUE
;
661 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
663 /* Create unique temporary file name */
664 GetTempFileName (szTempPath
, _T("CMD"), 0, szFileName
[1]);
666 /* Set current stdout to temporary file */
667 hFile
[1] = CreateFile (szFileName
[1], GENERIC_WRITE
, 0, &sa
,
668 TRUNCATE_EXISTING
, FILE_ATTRIBUTE_TEMPORARY
, NULL
);
669 if (hFile
[1] == INVALID_HANDLE_VALUE
)
671 LoadString(GetModuleHandle(NULL
), STRING_CMD_ERROR2
, szMsg
, RC_STRING_MAX_SIZE
);
676 SetStdHandle (STD_OUTPUT_HANDLE
, hFile
[1]);
680 /* close stdout file */
681 SetStdHandle (STD_OUTPUT_HANDLE
, hOldConOut
);
682 if ((hFile
[1] != INVALID_HANDLE_VALUE
) && (hFile
[1] != hOldConOut
))
684 CloseHandle (hFile
[1]);
685 hFile
[1] = INVALID_HANDLE_VALUE
;
688 /* close old stdin file */
689 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
690 if ((hFile
[0] != INVALID_HANDLE_VALUE
) && (hFile
[0] != hOldConIn
))
692 /* delete old stdin file, if it is a real file */
693 CloseHandle (hFile
[0]);
694 hFile
[0] = INVALID_HANDLE_VALUE
;
695 DeleteFile (szFileName
[0]);
696 *szFileName
[0] = _T('\0');
699 /* copy stdout file name to stdin file name */
700 _tcscpy (szFileName
[0], szFileName
[1]);
701 *szFileName
[1] = _T('\0');
703 /* open new stdin file */
704 hFile
[0] = CreateFile (szFileName
[0], GENERIC_READ
, 0, &sa
,
705 OPEN_EXISTING
, FILE_ATTRIBUTE_TEMPORARY
, NULL
);
706 SetStdHandle (STD_INPUT_HANDLE
, hFile
[0]);
708 s
= s
+ _tcslen (s
) + 1;
711 /* Now set up the end conditions... */
712 /* redirect STDOUT */
715 /* Final output to here */
717 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
719 hFile
= CreateFile (out
, GENERIC_WRITE
, FILE_SHARE_READ
, &sa
,
720 (nRedirFlags
& OUTPUT_APPEND
) ? OPEN_ALWAYS
: CREATE_ALWAYS
,
721 FILE_ATTRIBUTE_NORMAL
, NULL
);
722 if (hFile
== INVALID_HANDLE_VALUE
)
724 LoadString(GetModuleHandle(NULL
), STRING_CMD_ERROR3
, szMsg
, RC_STRING_MAX_SIZE
);
725 ConErrPrintf(szMsg
, out
);
729 if (!SetStdHandle (STD_OUTPUT_HANDLE
, hFile
))
731 LoadString(GetModuleHandle(NULL
), STRING_CMD_ERROR3
, szMsg
, RC_STRING_MAX_SIZE
);
732 ConErrPrintf(szMsg
, out
);
736 if (nRedirFlags
& OUTPUT_APPEND
)
740 if (GetFileType (hFile
) == FILE_TYPE_DISK
)
741 SetFilePointer (hFile
, 0, &lHighPos
, FILE_END
);
744 DebugPrintf (_T("Output redirected to: %s\n"), out
);
747 else if (hOldConOut
!= INVALID_HANDLE_VALUE
)
749 /* Restore original stdout */
750 HANDLE hOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
751 SetStdHandle (STD_OUTPUT_HANDLE
, hOldConOut
);
752 if (hOldConOut
!= hOut
)
754 hOldConOut
= INVALID_HANDLE_VALUE
;
757 /* redirect STDERR */
760 /* Final output to here */
762 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
764 if (!_tcscmp (err
, out
))
767 DebugPrintf (_T("Stdout and stderr will use the same file!!\n"));
769 DuplicateHandle (GetCurrentProcess (),
770 GetStdHandle (STD_OUTPUT_HANDLE
),
771 GetCurrentProcess (),
772 &hFile
, 0, TRUE
, DUPLICATE_SAME_ACCESS
);
776 hFile
= CreateFile (err
,
780 (nRedirFlags
& ERROR_APPEND
) ? OPEN_ALWAYS
: CREATE_ALWAYS
,
781 FILE_ATTRIBUTE_NORMAL
,
783 if (hFile
== INVALID_HANDLE_VALUE
)
785 LoadString(GetModuleHandle(NULL
), STRING_CMD_ERROR3
, szMsg
, RC_STRING_MAX_SIZE
);
786 ConErrPrintf(szMsg
, err
);
791 if (!SetStdHandle (STD_ERROR_HANDLE
, hFile
))
793 LoadString(GetModuleHandle(NULL
), STRING_CMD_ERROR3
, szMsg
, RC_STRING_MAX_SIZE
);
794 ConErrPrintf(szMsg
, err
);
798 if (nRedirFlags
& ERROR_APPEND
)
802 if (GetFileType (hFile
) == FILE_TYPE_DISK
)
803 SetFilePointer (hFile
, 0, &lHighPos
, FILE_END
);
806 DebugPrintf (_T("Error redirected to: %s\n"), err
);
809 else if (hOldConErr
!= INVALID_HANDLE_VALUE
)
811 /* Restore original stderr */
812 HANDLE hErr
= GetStdHandle (STD_ERROR_HANDLE
);
813 SetStdHandle (STD_ERROR_HANDLE
, hOldConErr
);
814 if (hOldConErr
!= hErr
)
816 hOldConErr
= INVALID_HANDLE_VALUE
;
820 /* process final command */
823 #ifdef FEATURE_REDIRECTION
824 /* close old stdin file */
825 #if 0 /* buggy implementation */
826 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
827 if ((hFile
[0] != INVALID_HANDLE_VALUE
) &&
828 (hFile
[0] != hOldConIn
))
830 /* delete old stdin file, if it is a real file */
831 CloseHandle (hFile
[0]);
832 hFile
[0] = INVALID_HANDLE_VALUE
;
833 DeleteFile (szFileName
[0]);
834 *szFileName
[0] = _T('\0');
837 /* Restore original STDIN */
838 if (hOldConIn
!= INVALID_HANDLE_VALUE
)
840 HANDLE hIn
= GetStdHandle (STD_INPUT_HANDLE
);
841 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
842 if (hOldConIn
!= hIn
)
844 hOldConIn
= INVALID_HANDLE_VALUE
;
849 DebugPrintf (_T("Can't restore STDIN! Is invalid!!\n"), out
);
852 #endif /* buggy implementation */
855 if (hOldConIn
!= INVALID_HANDLE_VALUE
)
857 HANDLE hIn
= GetStdHandle (STD_INPUT_HANDLE
);
858 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
859 if (hIn
== INVALID_HANDLE_VALUE
)
862 DebugPrintf (_T("Previous STDIN is invalid!!\n"));
867 if (GetFileType (hIn
) == FILE_TYPE_DISK
)
871 CloseHandle (hFile
[0]);
872 hFile
[0] = INVALID_HANDLE_VALUE
;
873 DeleteFile (szFileName
[0]);
874 *szFileName
[0] = _T('\0');
879 DebugPrintf (_T("hFile[0] and hIn dont match!!!\n"));
887 /* Restore original STDOUT */
888 if (hOldConOut
!= INVALID_HANDLE_VALUE
)
890 HANDLE hOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
891 SetStdHandle (STD_OUTPUT_HANDLE
, hOldConOut
);
892 if (hOldConOut
!= hOut
)
894 hOldConOut
= INVALID_HANDLE_VALUE
;
897 /* Restore original STDERR */
898 if (hOldConErr
!= INVALID_HANDLE_VALUE
)
900 HANDLE hErr
= GetStdHandle (STD_ERROR_HANDLE
);
901 SetStdHandle (STD_ERROR_HANDLE
, hOldConErr
);
902 if (hOldConErr
!= hErr
)
904 hOldConErr
= INVALID_HANDLE_VALUE
;
906 #endif /* FEATURE_REDIRECTION */
911 * do the prompt/input/process loop
916 ProcessInput (BOOL bFlag
)
918 TCHAR commandline
[CMDLINE_LENGTH
];
919 TCHAR readline
[CMDLINE_LENGTH
];
928 /* if no batch input then... */
929 if (!(ip
= ReadBatchLine (&bEchoThisLine
)))
934 ReadCommand (readline
, CMDLINE_LENGTH
);
936 bEchoThisLine
= FALSE
;
960 if ((tp
= FindArg (*ip
- _T('0'))))
962 cp
= _stpcpy (cp
, tp
);
970 cp
+= _stprintf (cp
, _T("%u"), nErrorLevel
);
975 tp
= _tcschr(ip
, _T('%'));
977 (tp
<= _tcschr(ip
, _T(' ')) - 1))
982 /* FIXME: This is just a quick hack!! */
983 /* Do a proper memory allocation!! */
984 if (GetEnvironmentVariable (ip
, evar
, 512))
985 cp
= _stpcpy (cp
, evar
);
1005 /* strip trailing spaces */
1006 while ((--cp
>= commandline
) && _istspace (*cp
));
1008 *(cp
+ 1) = _T('\0');
1011 /* Echo batch file line */
1015 ConOutPuts (commandline
);
1020 ParseCommandLine (commandline
);
1021 if (bEcho
&& !bIgnoreEcho
)
1023 bIgnoreEcho
= FALSE
;
1026 while (!bCanExit
|| !bExit
);
1033 * control-break handler.
1035 BOOL WINAPI
BreakHandler (DWORD dwCtrlType
)
1038 if ((dwCtrlType
!= CTRL_C_EVENT
) &&
1039 (dwCtrlType
!= CTRL_BREAK_EVENT
))
1042 if (bChildProcessRunning
== TRUE
)
1044 GenerateConsoleCtrlEvent (CTRL_C_EVENT
,
1049 /* FIXME: Handle batch files */
1051 /* FIXME: Print "^C" */
1058 VOID
AddBreakHandler (VOID
)
1060 SetConsoleCtrlHandler ((PHANDLER_ROUTINE
)BreakHandler
, TRUE
);
1064 VOID
RemoveBreakHandler (VOID
)
1066 SetConsoleCtrlHandler ((PHANDLER_ROUTINE
)BreakHandler
, FALSE
);
1071 * show commands and options that are available.
1078 TCHAR szMsg
[RC_STRING_MAX_SIZE
];
1080 /* print command list */
1081 LoadString(GetModuleHandle(NULL
), STRING_CMD_HELP1
, szMsg
, RC_STRING_MAX_SIZE
);
1082 ConOutPrintf(szMsg
);
1085 /* print feature list */
1086 LoadString(GetModuleHandle(NULL
), STRING_CMD_HELP2
, szMsg
, RC_STRING_MAX_SIZE
);
1089 #ifdef FEATURE_ALIASES
1090 LoadString(GetModuleHandle(NULL
), STRING_CMD_HELP3
, szMsg
, RC_STRING_MAX_SIZE
);
1093 #ifdef FEATURE_HISTORY
1094 LoadString(GetModuleHandle(NULL
), STRING_CMD_HELP4
, szMsg
, RC_STRING_MAX_SIZE
);
1097 #ifdef FEATURE_UNIX_FILENAME_COMPLETION
1098 LoadString(GetModuleHandle(NULL
), STRING_CMD_HELP5
, szMsg
, RC_STRING_MAX_SIZE
);
1101 #ifdef FEATURE_DIRECTORY_STACK
1102 LoadString(GetModuleHandle(NULL
), STRING_CMD_HELP6
, szMsg
, RC_STRING_MAX_SIZE
);
1105 #ifdef FEATURE_REDIRECTION
1106 LoadString(GetModuleHandle(NULL
), STRING_CMD_HELP7
, szMsg
, RC_STRING_MAX_SIZE
);
1109 ConOutChar(_T('\n'));
1114 * set up global initializations and process parameters
1116 * argc - number of parameters to command.com
1117 * argv - command-line parameters
1121 Initialize (int argc
, TCHAR
* argv
[])
1123 TCHAR szMsg
[RC_STRING_MAX_SIZE
];
1124 TCHAR commandline
[CMDLINE_LENGTH
];
1125 TCHAR ModuleName
[_MAX_PATH
+ 1];
1129 //TCHAR *ptr, *cmdLine;
1135 DebugPrintf (_T("[command args:\n"));
1136 for (x
= 0; x
< argc
; x
++)
1138 DebugPrintf (_T("%d. %s\n"), x
, argv
[x
]);
1140 DebugPrintf (_T("]\n"));
1143 /* get version information */
1144 osvi
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
1145 GetVersionEx (&osvi
);
1149 /* get default input and output console handles */
1150 hOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
1151 hIn
= GetStdHandle (STD_INPUT_HANDLE
);
1154 if (argc
>= 2 && !_tcsncmp (argv
[1], _T("/?"), 2))
1156 LoadString(GetModuleHandle(NULL
), STRING_CMD_HELP8
, szMsg
, RC_STRING_MAX_SIZE
);
1160 SetConsoleMode (hIn
, ENABLE_PROCESSED_INPUT
);
1162 #ifdef INCLUDE_CMD_CHDIR
1166 #ifdef FATURE_ALIASES
1172 for (i
= 1; i
< argc
; i
++)
1174 if (!_tcsicmp (argv
[i
], _T("/p")))
1176 if (!IsExistingFile (_T("\\autoexec.bat")))
1178 #ifdef INCLUDE_CMD_DATE
1179 cmd_date (_T(""), _T(""));
1181 #ifdef INCLUDE_CMD_TIME
1182 cmd_time (_T(""), _T(""));
1187 ParseCommandLine (_T("\\autoexec.bat"));
1191 else if (!_tcsicmp (argv
[i
], _T("/c")))
1193 /* This just runs a program and exits */
1197 _tcscpy (commandline
, argv
[i
]);
1200 _tcscat (commandline
, _T(" "));
1201 _tcscat (commandline
, argv
[i
]);
1204 ParseCommandLine(commandline
);
1205 ExitProcess (ProcessInput (TRUE
));
1212 else if (!_tcsicmp (argv
[i
], _T("/k")))
1214 /* This just runs a program and remains */
1218 _tcscpy (commandline
, argv
[i
]);
1221 _tcscat (commandline
, _T(" "));
1222 _tcscat (commandline
, argv
[i
]);
1225 ParseCommandLine(commandline
);
1228 #ifdef INCLUDE_CMD_COLOR
1229 else if (!_tcsnicmp (argv
[i
], _T("/t:"), 3))
1231 /* process /t (color) argument */
1232 wDefColor
= (WORD
)_tcstoul (&argv
[i
][3], NULL
, 16);
1234 SetScreenColor (wColor
, TRUE
);
1240 /* run cmdstart.bat */
1241 if (IsExistingFile (_T("cmdstart.bat")))
1243 ParseCommandLine (_T("cmdstart.bat"));
1245 else if (IsExistingFile (_T("\\cmdstart.bat")))
1247 ParseCommandLine (_T("\\cmdstart.bat"));
1252 /* try to run cmdstart.bat from install dir */
1255 _tcscpy (commandline
, argv
[0]);
1256 p
= _tcsrchr (commandline
, _T('\\')) + 1;
1257 _tcscpy (p
, _T("cmdstart.bat"));
1259 if (IsExistingFile (_T("commandline")))
1261 LoadString(GetModuleHandle(NULL
), STRING_CMD_ERROR4
, szMsg
, RC_STRING_MAX_SIZE
);
1262 ConErrPrintf(szMsg
, commandline
);
1263 ParseCommandLine (commandline
);
1268 #ifdef FEATURE_DIR_STACK
1269 /* initialize directory stack */
1270 InitDirectoryStack ();
1274 #ifdef FEATURE_HISTORY
1275 /*initialize history*/
1279 /* Set COMSPEC environment variable */
1280 if (0 != GetModuleFileName (NULL
, ModuleName
, _MAX_PATH
+ 1))
1282 ModuleName
[_MAX_PATH
] = _T('\0');
1283 SetEnvironmentVariable (_T("COMSPEC"), ModuleName
);
1286 /* add ctrl break handler */
1291 static VOID
Cleanup (int argc
, TCHAR
*argv
[])
1293 TCHAR szMsg
[RC_STRING_MAX_SIZE
];
1295 /* run cmdexit.bat */
1296 if (IsExistingFile (_T("cmdexit.bat")))
1298 LoadString(GetModuleHandle(NULL
), STRING_CMD_ERROR5
, szMsg
, RC_STRING_MAX_SIZE
);
1299 ConErrPrintf(szMsg
);
1301 ParseCommandLine (_T("cmdexit.bat"));
1303 else if (IsExistingFile (_T("\\cmdexit.bat")))
1305 LoadString( GetModuleHandle(NULL
), STRING_CMD_ERROR5
, szMsg
, RC_STRING_MAX_SIZE
);
1306 ConErrPrintf ((LPTSTR
)szMsg
);
1307 ParseCommandLine (_T("\\cmdexit.bat"));
1312 /* try to run cmdexit.bat from install dir */
1313 TCHAR commandline
[CMDLINE_LENGTH
];
1316 _tcscpy (commandline
, argv
[0]);
1317 p
= _tcsrchr (commandline
, _T('\\')) + 1;
1318 _tcscpy (p
, _T("cmdexit.bat"));
1320 if (IsExistingFile (_T("commandline")))
1322 LoadString(GetModuleHandle(NULL
), STRING_CMD_ERROR4
, szMsg
, RC_STRING_MAX_SIZE
);
1323 ConErrPrintf(szMsg
, commandline
);
1324 ParseCommandLine (commandline
);
1329 #ifdef FEATURE_ALIASES
1333 #ifdef FEATURE_DIECTORY_STACK
1334 /* destroy directory stack */
1335 DestroyDirectoryStack ();
1338 #ifdef INCLUDE_CMD_CHDIR
1342 #ifdef FEATURE_HISTORY
1347 /* remove ctrl break handler */
1348 RemoveBreakHandler ();
1349 SetConsoleMode( GetStdHandle( STD_INPUT_HANDLE
),
1350 ENABLE_LINE_INPUT
| ENABLE_PROCESSED_INPUT
| ENABLE_ECHO_INPUT
);
1355 PWCHAR
* _CommandLineToArgvW(PWCHAR lpCmdLine
, int *pNumArgs
)
1357 PWCHAR
* argvw
= NULL
;
1358 PWCHAR ptr
= lpCmdLine
;
1365 while(lpCmdLine
&& *lpCmdLine
)
1367 while (iswspace(*lpCmdLine
)) lpCmdLine
++;
1370 if ((NumArgs
% 10)==0)
1372 PWCHAR
* old_argvw
= argvw
;
1373 argvw
= malloc((NumArgs
+ 10) * sizeof(PWCHAR
));
1374 memcpy(argvw
, old_argvw
, NumArgs
* sizeof(PWCHAR
));
1377 ptr
= wcschr(lpCmdLine
, L
' ');
1380 len
= ptr
- lpCmdLine
;
1384 len
= wcslen(lpCmdLine
);
1386 str
= malloc((len
+ 1) * sizeof(WCHAR
));
1387 memcpy(str
, lpCmdLine
, len
* sizeof(WCHAR
));
1394 *pNumArgs
= NumArgs
;
1406 int main (int argc
, char *argv
[])
1409 CONSOLE_SCREEN_BUFFER_INFO Info
;
1415 argv
= _CommandLineToArgvW(GetCommandLineW(), &argc
);
1417 argv
= CommandLineToArgvW(GetCommandLineW(), &argc
);
1425 hConsole
= CreateFile(_T("CONOUT$"), GENERIC_READ
|GENERIC_WRITE
,
1426 FILE_SHARE_READ
|FILE_SHARE_WRITE
, NULL
,
1427 OPEN_EXISTING
, 0, NULL
);
1428 if (GetConsoleScreenBufferInfo(hConsole
, &Info
) == FALSE
)
1430 ConOutFormatMessage(GetLastError());
1433 wColor
= Info
.wAttributes
;
1436 GetCodePage
= GetConsoleCP();
1437 OutCodePage
= GetConsoleOutputCP();
1439 /* check switches on command-line */
1440 Initialize(argc
, argv
);
1442 /* call prompt routine */
1443 nExitCode
= ProcessInput(FALSE
);
1445 /* do the cleanup */
1446 Cleanup(argc
, argv
);