1 /* $Id: cmd.c,v 1.19 2004/08/22 20:47:20 hbirr Exp $
3 * CMD.C - command-line interface.
8 * 17 Jun 1994 (Tim Norman)
11 * 08 Aug 1995 (Matt Rains)
12 * I have cleaned up the source code. changes now bring this source
13 * into guidelines for recommended programming practice.
15 * A added the the standard FreeDOS GNU licence test to the
16 * initialize() function.
18 * Started to replace puts() with printf(). this will help
19 * standardize output. please follow my lead.
21 * I have added some constants to help making changes easier.
23 * 15 Dec 1995 (Tim Norman)
24 * major rewrite of the code to make it more efficient and add
25 * redirection support (finally!)
27 * 06 Jan 1996 (Tim Norman)
28 * finished adding redirection support! Changed to use our own
29 * exec code (MUCH thanks to Svante Frey!!)
31 * 29 Jan 1996 (Tim Norman)
32 * added support for CHDIR, RMDIR, MKDIR, and ERASE, as per
33 * suggestion of Steffan Kaiser
35 * changed "file not found" error message to "bad command or
36 * filename" thanks to Dustin Norman for noticing that confusing
39 * changed the format to call internal commands (again) so that if
40 * they want to split their commands, they can do it themselves
41 * (none of the internal functions so far need that much power, anyway)
43 * 27 Aug 1996 (Tim Norman)
44 * added in support for Oliver Mueller's ALIAS command
46 * 14 Jun 1997 (Steffan Kaiser)
47 * added ctrl-break handling and error level
49 * 16 Jun 1998 (Rob Lake)
50 * Runs command.com if /P is specified in command line. Command.com
51 * also stays permanent. If /C is in the command line, starts the
52 * program next in the line.
54 * 21 Jun 1998 (Rob Lake)
55 * Fixed up /C so that arguments for the program
57 * 08-Jul-1998 (John P. Price)
58 * Now sets COMSPEC environment variable
59 * misc clean up and optimization
60 * added date and time commands
61 * changed to using spawnl instead of exec. exec does not copy the
62 * environment to the child process!
64 * 14 Jul 1998 (Hans B Pufal)
65 * Reorganised source to be more efficient and to more closely
66 * follow MS-DOS conventions. (eg %..% environment variable
67 * replacement works form command line as well as batch file.
69 * New organisation also properly support nested batch files.
71 * New command table structure is half way towards providing a
72 * system in which COMMAND will find out what internal commands
75 * 24 Jul 1998 (Hans B Pufal) [HBP_003]
76 * Fixed return value when called with /C option
78 * 27 Jul 1998 John P. Price
79 * added config.h include
81 * 28 Jul 1998 John P. Price
82 * added showcmds function to show commands and options available
84 * 07-Aug-1998 (John P Price <linux-guru@gcfl.net>)
85 * Fixed carrage return output to better match MSDOS with echo
86 * on or off. (marked with "JPP 19980708")
88 * 07-Dec-1998 (Eric Kohl <ekohl@abo.rhein-zeitung.de>)
89 * First ReactOS release.
90 * Extended length of commandline buffers to 512.
92 * 13-Dec-1998 (Eric Kohl <ekohl@abo.rhein-zeitung.de>)
93 * Added COMSPEC environment variable.
94 * Added "/t" support (color) on cmd command line.
96 * 07-Jan-1999 (Eric Kohl <ekohl@abo.rhein-zeitung.de>)
97 * Added help text ("cmd /?").
99 * 25-Jan-1999 (Eric Kohl <ekohl@abo.rhein-zeitung.de>)
100 * Unicode and redirection safe!
101 * Fixed redirections and piping.
102 * Piping is based on temporary files, but basic support
103 * for anonymous pipes already exists.
105 * 27-Jan-1999 (Eric Kohl <ekohl@abo.rhein-zeitung.de>)
106 * Replaced spawnl() by CreateProcess().
108 * 22-Oct-1999 (Eric Kohl <ekohl@abo.rhein-zeitung.de>)
109 * Added break handler.
111 * 15-Dec-1999 (Eric Kohl <ekohl@abo.rhein-zeitung.de>)
112 * Fixed current directory
114 * 28-Dec-1999 (Eric Kohl <ekohl@abo.rhein-zeitung.de>)
115 * Restore window title after program/batch execution
117 * 03-Feb-2001 (Eric Kohl <ekohl@rz-online.de>)
118 * Workaround because argc[0] is NULL under ReactOS
120 * 23-Feb-2001 (Carl Nettelblad <cnettel@hem.passagen.se>)
121 * %envvar% replacement conflicted with for.
123 * 30-Apr-2004 (Filip Navara <xnavara@volny.cz>)
124 * Make MakeSureDirectoryPathExistsEx unicode safe.
126 * 28-Mai-2004 (Hartmut Birr)
127 * Removed MakeSureDirectoryPathExistsEx.
128 * Use the current directory if GetTempPath fails.
130 * 12-Jul-2004 (Jens Collin <jens.collin@lakhei.com>)
131 * Added ShellExecute call when all else fails to be able to "launch" any file.
143 #include <winternl.h>
146 #define NT_SUCCESS(StatCode) ((NTSTATUS)(StatCode) >= 0)
151 #include <shellapi.h>
153 typedef NTSTATUS (STDCALL
*NtQueryInformationProcessProc
)(HANDLE
, PROCESSINFOCLASS
,
154 PVOID
, ULONG
, PULONG
);
155 typedef NTSTATUS (STDCALL
*NtReadVirtualMemoryProc
)(HANDLE
, PVOID
, PVOID
, ULONG
, PULONG
);
157 BOOL bExit
= FALSE
; /* indicates EXIT was typed */
158 BOOL bCanExit
= TRUE
; /* indicates if this shell is exitable */
159 BOOL bCtrlBreak
= FALSE
; /* Ctrl-Break or Ctrl-C hit */
160 BOOL bIgnoreEcho
= FALSE
; /* Ignore 'newline' before 'cls' */
161 INT nErrorLevel
= 0; /* Errorlevel of last launched external program */
162 BOOL bChildProcessRunning
= FALSE
;
163 DWORD dwChildProcessId
= 0;
169 static NtQueryInformationProcessProc NtQueryInformationProcessPtr
;
170 static NtReadVirtualMemoryProc NtReadVirtualMemoryPtr
;
171 static BOOL NtDllChecked
= FALSE
;
173 #ifdef INCLUDE_CMD_COLOR
174 WORD wColor
; /* current color */
175 WORD wDefColor
; /* default color */
179 * is character a delimeter when used on first word?
183 static BOOL
IsDelimiter (TCHAR c
)
185 return (c
== _T('/') || c
== _T('=') || c
== _T('\0') || _istspace (c
));
189 * Is a process a console process?
191 static BOOL
IsConsoleProcess(HANDLE Process
)
194 PROCESS_BASIC_INFORMATION Info
;
199 /* Some people like to run ReactOS cmd.exe on Win98, it helps in the
200 build process. So don't link implicitly against ntdll.dll, load it
201 dynamically instead */
205 NtDllModule
= LoadLibrary(_T("ntdll.dll"));
206 if (NULL
== NtDllModule
)
208 /* Probably non-WinNT system. Just wait for the commands
210 NtQueryInformationProcessPtr
= NULL
;
211 NtReadVirtualMemoryPtr
= NULL
;
214 NtQueryInformationProcessPtr
= (NtQueryInformationProcessProc
)
215 GetProcAddress(NtDllModule
, "NtQueryInformationProcess");
216 NtReadVirtualMemoryPtr
= (NtReadVirtualMemoryProc
)
217 GetProcAddress(NtDllModule
, "NtReadVirtualMemory");
220 if (NULL
== NtQueryInformationProcessPtr
|| NULL
== NtReadVirtualMemoryPtr
)
225 Status
= NtQueryInformationProcessPtr(Process
, ProcessBasicInformation
,
226 &Info
, sizeof(PROCESS_BASIC_INFORMATION
), NULL
);
227 if (! NT_SUCCESS(Status
))
230 DebugPrintf (_T("NtQueryInformationProcess failed with status %08x\n"), Status
);
234 Status
= NtReadVirtualMemoryPtr(Process
, Info
.PebBaseAddress
, &ProcessPeb
,
235 sizeof(PEB
), &BytesRead
);
236 if (! NT_SUCCESS(Status
) || sizeof(PEB
) != BytesRead
)
239 DebugPrintf (_T("Couldn't read virt mem status %08x bytes read %lu\n"), Status
, BytesRead
);
244 return IMAGE_SUBSYSTEM_WINDOWS_CUI
== ProcessPeb
.ImageSubSystem
;
250 #define SHELLEXECUTETEXT "ShellExecuteW"
252 #define SHELLEXECUTETEXT "ShellExecuteA"
255 typedef HINSTANCE (WINAPI
*MYEX
)(
259 LPCTSTR lpParameters
,
266 static BOOL
RunFile(LPTSTR filename
)
273 DebugPrintf (_T("RunFile(%s)\n"), filename
);
275 hShell32
= LoadLibrary(_T("SHELL32.DLL"));
279 DebugPrintf (_T("RunFile: couldn't load SHELL32.DLL!\n"));
284 hShExt
= (MYEX
)(FARPROC
)GetProcAddress(hShell32
, SHELLEXECUTETEXT
);
288 DebugPrintf (_T("RunFile: couldn't find ShellExecuteA/W in SHELL32.DLL!\n"));
290 FreeLibrary(hShell32
);
295 DebugPrintf (_T("RunFile: ShellExecuteA/W is at %x\n"), hShExt
);
298 ret
= (hShExt
)(NULL
, _T("open"), filename
, NULL
, NULL
, SW_SHOWNORMAL
);
301 DebugPrintf (_T("RunFile: ShellExecuteA/W returned %d\n"), (DWORD
)ret
);
304 FreeLibrary(hShell32
);
305 return (((DWORD
)ret
) > 32);
311 * This command (in first) was not found in the command table
313 * first - first word on command line
314 * rest - rest of command line
318 Execute (LPTSTR full
, LPTSTR first
, LPTSTR rest
)
320 TCHAR szFullName
[MAX_PATH
];
322 TCHAR szWindowTitle
[MAX_PATH
];
324 DWORD dwExitCode
= 0;
327 DebugPrintf (_T("Execute: \'%s\' \'%s\'\n"), first
, rest
);
330 /* check for a drive change */
331 if ((_istalpha (first
[0])) && (!_tcscmp (first
+ 1, _T(":"))))
334 if (!SetCurrentDirectory(first
))
335 /* Guess they changed disc or something, handle that gracefully and get to root */
342 working
= SetCurrentDirectory(str
);
345 if (!working
) ConErrPuts (INVALIDDRIVE
);
350 /* get the PATH environment variable and parse it */
351 /* search the PATH environment variable for the binary */
352 if (!SearchForExecutable (first
, szFullName
))
354 error_bad_command ();
359 GetConsoleTitle (szWindowTitle
, MAX_PATH
);
362 /* check if this is a .BAT or .CMD file */
363 if (!_tcsicmp (_tcsrchr (szFullName
, _T('.')), _T(".bat")) ||
364 !_tcsicmp (_tcsrchr (szFullName
, _T('.')), _T(".cmd")))
367 DebugPrintf (_T("[BATCH: %s %s]\n"), szFullName
, rest
);
369 Batch (szFullName
, first
, rest
);
373 /* exec the program */
374 PROCESS_INFORMATION prci
;
378 DebugPrintf (_T("[EXEC: %s %s]\n"), full
, rest
);
380 /* build command line for CreateProcess() */
382 /* fill startup info */
383 memset (&stui
, 0, sizeof (STARTUPINFO
));
384 stui
.cb
= sizeof (STARTUPINFO
);
385 stui
.dwFlags
= STARTF_USESHOWWINDOW
;
386 stui
.wShowWindow
= SW_SHOWDEFAULT
;
388 // return console to standard mode
389 SetConsoleMode (GetStdHandle(STD_INPUT_HANDLE
),
390 ENABLE_LINE_INPUT
| ENABLE_PROCESSED_INPUT
| ENABLE_ECHO_INPUT
);
392 if (CreateProcess (szFullName
,
397 CREATE_NEW_PROCESS_GROUP
,
403 if (IsConsoleProcess(prci
.hProcess
))
405 /* FIXME: Protect this with critical section */
406 bChildProcessRunning
= TRUE
;
407 dwChildProcessId
= prci
.dwProcessId
;
409 WaitForSingleObject (prci
.hProcess
, INFINITE
);
411 /* FIXME: Protect this with critical section */
412 bChildProcessRunning
= FALSE
;
414 GetExitCodeProcess (prci
.hProcess
, &dwExitCode
);
415 nErrorLevel
= (INT
)dwExitCode
;
417 CloseHandle (prci
.hThread
);
418 CloseHandle (prci
.hProcess
);
423 DebugPrintf (_T("[ShellExecute: %s]\n"), full
);
425 // See if we can run this with ShellExecute() ie myfile.xls
429 DebugPrintf (_T("[ShellExecute failed!: %s]\n"), full
);
431 error_bad_command ();
434 // restore console mode
435 SetConsoleMode( GetStdHandle( STD_INPUT_HANDLE
),
436 ENABLE_PROCESSED_INPUT
);
440 SetConsoleTitle (szWindowTitle
);
446 * look through the internal commands and determine whether or not this
447 * command is one of them. If it is, call the command. If not, call
448 * execute to run it as an external program.
450 * line - the command line of the program to run
455 DoCommand (LPTSTR line
)
457 TCHAR com
[CMDLINE_LENGTH
]; /* the first word in the command */
460 LPTSTR rest
; /* pointer to the rest of the command line */
465 DebugPrintf (_T("DoCommand: (\'%s\')\n"), line
);
468 /* Skip over initial white space */
469 while (_istspace (*line
))
475 /* Anything to do ? */
478 if (*rest
== _T('"'))
480 /* treat quoted words specially */
484 while(*rest
!= _T('\0') && *rest
!= _T('"'))
485 *cp
++ = _totlower (*rest
++);
486 if (*rest
== _T('"'))
491 while (!IsDelimiter (*rest
))
492 *cp
++ = _totlower (*rest
++);
496 /* Terminate first word */
499 /* commands are limited to MAX_PATH */
500 if(_tcslen(com
) > MAX_PATH
)
506 /* Skip over whitespace to rest of line */
507 while (_istspace (*rest
))
510 /* Scan internal command table */
511 for (cmdptr
= cmds
;; cmdptr
++)
513 /* If end of table execute ext cmd */
514 if (cmdptr
->name
== NULL
)
516 Execute (line
, com
, rest
);
520 if (!_tcscmp (com
, cmdptr
->name
))
522 cmdptr
->func (com
, rest
);
526 /* The following code handles the case of commands like CD which
527 * are recognised even when the command name and parameter are
528 * not space separated.
534 /* Get length of command name */
535 cl
= _tcslen (cmdptr
->name
);
537 if ((cmdptr
->flags
& CMD_SPECIAL
) &&
538 (!_tcsncmp (cmdptr
->name
, com
, cl
)) &&
539 (_tcschr (_T("\\.-"), *(com
+ cl
))))
541 /* OK its one of the specials...*/
543 /* Terminate first word properly */
546 /* Call with new rest */
547 cmdptr
->func (com
, cstart
+ cl
);
556 * process the command line and execute the appropriate functions
557 * full input/output redirection and piping are supported
560 VOID
ParseCommandLine (LPTSTR cmd
)
562 TCHAR cmdline
[CMDLINE_LENGTH
];
564 #ifdef FEATURE_REDIRECTION
565 TCHAR in
[CMDLINE_LENGTH
] = _T("");
566 TCHAR out
[CMDLINE_LENGTH
] = _T("");
567 TCHAR err
[CMDLINE_LENGTH
] = _T("");
568 TCHAR szTempPath
[MAX_PATH
] = _T(".\\");
569 TCHAR szFileName
[2][MAX_PATH
] = {_T(""), _T("")};
570 HANDLE hFile
[2] = {INVALID_HANDLE_VALUE
, INVALID_HANDLE_VALUE
};
580 #endif /* FEATURE_REDIRECTION */
582 _tcscpy (cmdline
, cmd
);
586 DebugPrintf (_T("ParseCommandLine: (\'%s\')\n"), s
);
589 #ifdef FEATURE_ALIASES
590 /* expand all aliases */
591 ExpandAlias (s
, CMDLINE_LENGTH
);
592 #endif /* FEATURE_ALIAS */
594 #ifdef FEATURE_REDIRECTION
595 /* find the temp path to store temporary files */
596 Length
= GetTempPath (MAX_PATH
, szTempPath
);
597 if (Length
> 0 && Length
< MAX_PATH
)
599 Attributes
= GetFileAttributes(szTempPath
);
600 if (Attributes
== 0xffffffff ||
601 !(Attributes
& FILE_ATTRIBUTE_DIRECTORY
))
606 if (Length
== 0 || Length
>= MAX_PATH
)
608 _tcscpy(szTempPath
, _T(".\\"));
610 if (szTempPath
[_tcslen (szTempPath
) - 1] != _T('\\'))
611 _tcscat (szTempPath
, _T("\\"));
613 /* get the redirections from the command line */
614 num
= GetRedirection (s
, in
, out
, err
, &nRedirFlags
);
616 /* more efficient, but do we really need to do this? */
617 for (t
= in
; _istspace (*t
); t
++)
621 for (t
= out
; _istspace (*t
); t
++)
625 for (t
= err
; _istspace (*t
); t
++)
629 /* Set up the initial conditions ... */
630 /* preserve STDIN, STDOUT and STDERR handles */
631 hOldConIn
= GetStdHandle (STD_INPUT_HANDLE
);
632 hOldConOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
633 hOldConErr
= GetStdHandle (STD_ERROR_HANDLE
);
639 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
641 hFile
= CreateFile (in
, GENERIC_READ
, FILE_SHARE_READ
, &sa
, OPEN_EXISTING
,
642 FILE_ATTRIBUTE_NORMAL
, NULL
);
643 if (hFile
== INVALID_HANDLE_VALUE
)
645 ConErrPrintf (_T("Can't redirect input from file %s\n"), in
);
649 if (!SetStdHandle (STD_INPUT_HANDLE
, hFile
))
651 ConErrPrintf (_T("Can't redirect input from file %s\n"), in
);
655 DebugPrintf (_T("Input redirected from: %s\n"), in
);
659 /* Now do all but the last pipe command */
660 *szFileName
[0] = _T('\0');
661 hFile
[0] = INVALID_HANDLE_VALUE
;
665 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
667 /* Create unique temporary file name */
668 GetTempFileName (szTempPath
, _T("CMD"), 0, szFileName
[1]);
670 /* Set current stdout to temporary file */
671 hFile
[1] = CreateFile (szFileName
[1], GENERIC_WRITE
, 0, &sa
,
672 TRUNCATE_EXISTING
, FILE_ATTRIBUTE_TEMPORARY
, NULL
);
674 if (hFile
[1] == INVALID_HANDLE_VALUE
){
675 ConErrPrintf (_T("Error creating temporary file for pipe data\n"));
679 SetStdHandle (STD_OUTPUT_HANDLE
, hFile
[1]);
683 /* close stdout file */
684 SetStdHandle (STD_OUTPUT_HANDLE
, hOldConOut
);
685 if ((hFile
[1] != INVALID_HANDLE_VALUE
) && (hFile
[1] != hOldConOut
))
687 CloseHandle (hFile
[1]);
688 hFile
[1] = INVALID_HANDLE_VALUE
;
691 /* close old stdin file */
692 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
693 if ((hFile
[0] != INVALID_HANDLE_VALUE
) && (hFile
[0] != hOldConIn
))
695 /* delete old stdin file, if it is a real file */
696 CloseHandle (hFile
[0]);
697 hFile
[0] = INVALID_HANDLE_VALUE
;
698 DeleteFile (szFileName
[0]);
699 *szFileName
[0] = _T('\0');
702 /* copy stdout file name to stdin file name */
703 _tcscpy (szFileName
[0], szFileName
[1]);
704 *szFileName
[1] = _T('\0');
706 /* open new stdin file */
707 hFile
[0] = CreateFile (szFileName
[0], GENERIC_READ
, 0, &sa
,
708 OPEN_EXISTING
, FILE_ATTRIBUTE_TEMPORARY
, NULL
);
709 SetStdHandle (STD_INPUT_HANDLE
, hFile
[0]);
711 s
= s
+ _tcslen (s
) + 1;
714 /* Now set up the end conditions... */
715 /* redirect STDOUT */
718 /* Final output to here */
720 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
722 hFile
= CreateFile (out
, GENERIC_WRITE
, FILE_SHARE_READ
, &sa
,
723 (nRedirFlags
& OUTPUT_APPEND
) ? OPEN_ALWAYS
: CREATE_ALWAYS
,
724 FILE_ATTRIBUTE_NORMAL
, NULL
);
725 if (hFile
== INVALID_HANDLE_VALUE
)
727 ConErrPrintf (_T("Can't redirect to file %s\n"), out
);
731 if (!SetStdHandle (STD_OUTPUT_HANDLE
, hFile
))
733 ConErrPrintf (_T("Can't redirect to file %s\n"), 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 ConErrPrintf (_T("Can't redirect to file %s\n"), err
);
790 if (!SetStdHandle (STD_ERROR_HANDLE
, hFile
))
792 ConErrPrintf (_T("Can't redirect to file %s\n"), err
);
796 if (nRedirFlags
& ERROR_APPEND
)
800 if (GetFileType (hFile
) == FILE_TYPE_DISK
)
801 SetFilePointer (hFile
, 0, &lHighPos
, FILE_END
);
804 DebugPrintf (_T("Error redirected to: %s\n"), err
);
807 else if (hOldConErr
!= INVALID_HANDLE_VALUE
)
809 /* Restore original stderr */
810 HANDLE hErr
= GetStdHandle (STD_ERROR_HANDLE
);
811 SetStdHandle (STD_ERROR_HANDLE
, hOldConErr
);
812 if (hOldConErr
!= hErr
)
814 hOldConErr
= INVALID_HANDLE_VALUE
;
818 /* process final command */
821 #ifdef FEATURE_REDIRECTION
822 /* close old stdin file */
823 #if 0 /* buggy implementation */
824 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
825 if ((hFile
[0] != INVALID_HANDLE_VALUE
) &&
826 (hFile
[0] != hOldConIn
))
828 /* delete old stdin file, if it is a real file */
829 CloseHandle (hFile
[0]);
830 hFile
[0] = INVALID_HANDLE_VALUE
;
831 DeleteFile (szFileName
[0]);
832 *szFileName
[0] = _T('\0');
835 /* Restore original STDIN */
836 if (hOldConIn
!= INVALID_HANDLE_VALUE
)
838 HANDLE hIn
= GetStdHandle (STD_INPUT_HANDLE
);
839 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
840 if (hOldConIn
!= hIn
)
842 hOldConIn
= INVALID_HANDLE_VALUE
;
847 DebugPrintf (_T("Can't restore STDIN! Is invalid!!\n"), out
);
850 #endif /* buggy implementation */
853 if (hOldConIn
!= INVALID_HANDLE_VALUE
)
855 HANDLE hIn
= GetStdHandle (STD_INPUT_HANDLE
);
856 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
857 if (hIn
== INVALID_HANDLE_VALUE
)
860 DebugPrintf (_T("Previous STDIN is invalid!!\n"));
865 if (GetFileType (hIn
) == FILE_TYPE_DISK
)
869 CloseHandle (hFile
[0]);
870 hFile
[0] = INVALID_HANDLE_VALUE
;
871 DeleteFile (szFileName
[0]);
872 *szFileName
[0] = _T('\0');
877 DebugPrintf (_T("hFile[0] and hIn dont match!!!\n"));
885 /* Restore original STDOUT */
886 if (hOldConOut
!= INVALID_HANDLE_VALUE
)
888 HANDLE hOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
889 SetStdHandle (STD_OUTPUT_HANDLE
, hOldConOut
);
890 if (hOldConOut
!= hOut
)
892 hOldConOut
= INVALID_HANDLE_VALUE
;
895 /* Restore original STDERR */
896 if (hOldConErr
!= INVALID_HANDLE_VALUE
)
898 HANDLE hErr
= GetStdHandle (STD_ERROR_HANDLE
);
899 SetStdHandle (STD_ERROR_HANDLE
, hOldConErr
);
900 if (hOldConErr
!= hErr
)
902 hOldConErr
= INVALID_HANDLE_VALUE
;
904 #endif /* FEATURE_REDIRECTION */
909 * do the prompt/input/process loop
914 ProcessInput (BOOL bFlag
)
916 TCHAR commandline
[CMDLINE_LENGTH
];
917 TCHAR readline
[CMDLINE_LENGTH
];
925 /* if no batch input then... */
926 if (!(ip
= ReadBatchLine (&bEchoThisLine
)))
931 ReadCommand (readline
, CMDLINE_LENGTH
);
933 bEchoThisLine
= FALSE
;
957 if ((tp
= FindArg (*ip
- _T('0'))))
959 cp
= _stpcpy (cp
, tp
);
967 cp
+= _stprintf (cp
, _T("%u"), nErrorLevel
);
972 tp
= _tcschr(ip
, _T('%'));
974 (tp
<= _tcschr(ip
, _T(' ')) - 1))
979 /* FIXME: This is just a quick hack!! */
980 /* Do a proper memory allocation!! */
981 if (GetEnvironmentVariable (ip
, evar
, 512))
982 cp
= _stpcpy (cp
, evar
);
1002 /* strip trailing spaces */
1003 while ((--cp
>= commandline
) && _istspace (*cp
));
1005 *(cp
+ 1) = _T('\0');
1008 /* Echo batch file line */
1012 ConOutPuts (commandline
);
1017 ParseCommandLine (commandline
);
1018 if (bEcho
&& !bIgnoreEcho
)
1020 bIgnoreEcho
= FALSE
;
1023 while (!bCanExit
|| !bExit
);
1030 * control-break handler.
1032 BOOL WINAPI
BreakHandler (DWORD dwCtrlType
)
1034 if ((dwCtrlType
!= CTRL_C_EVENT
) &&
1035 (dwCtrlType
!= CTRL_BREAK_EVENT
))
1038 if (bChildProcessRunning
== TRUE
)
1040 GenerateConsoleCtrlEvent (CTRL_C_EVENT
,
1045 /* FIXME: Handle batch files */
1047 /* FIXME: Print "^C" */
1054 VOID
AddBreakHandler (VOID
)
1056 SetConsoleCtrlHandler ((PHANDLER_ROUTINE
)BreakHandler
, TRUE
);
1060 VOID
RemoveBreakHandler (VOID
)
1062 SetConsoleCtrlHandler ((PHANDLER_ROUTINE
)BreakHandler
, FALSE
);
1067 * show commands and options that are available.
1074 /* print command list */
1075 ConOutPrintf (_T("\nInternal commands available:\n"));
1076 PrintCommandList ();
1078 /* print feature list */
1079 ConOutPuts (_T("\nFeatures available:"));
1080 #ifdef FEATURE_ALIASES
1081 ConOutPuts (_T(" [aliases]"));
1083 #ifdef FEATURE_HISTORY
1084 ConOutPuts (_T(" [history]"));
1086 #ifdef FEATURE_UNIX_FILENAME_COMPLETION
1087 ConOutPuts (_T(" [unix filename completion]"));
1089 #ifdef FEATURE_DIRECTORY_STACK
1090 ConOutPuts (_T(" [directory stack]"));
1092 #ifdef FEATURE_REDIRECTION
1093 ConOutPuts (_T(" [redirections and piping]"));
1095 ConOutChar (_T('\n'));
1100 * set up global initializations and process parameters
1102 * argc - number of parameters to command.com
1103 * argv - command-line parameters
1107 Initialize (int argc
, TCHAR
* argv
[])
1109 TCHAR commandline
[CMDLINE_LENGTH
];
1110 TCHAR ModuleName
[_MAX_PATH
+ 1];
1113 //TCHAR *ptr, *cmdLine;
1119 DebugPrintf (_T("[command args:\n"));
1120 for (x
= 0; x
< argc
; x
++)
1122 DebugPrintf (_T("%d. %s\n"), x
, argv
[x
]);
1124 DebugPrintf (_T("]\n"));
1127 /* get version information */
1128 osvi
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
1129 GetVersionEx (&osvi
);
1133 /* get default input and output console handles */
1134 hOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
1135 hIn
= GetStdHandle (STD_INPUT_HANDLE
);
1138 if (argc
>= 2 && !_tcsncmp (argv
[1], _T("/?"), 2))
1140 ConOutPuts (_T("Starts a new instance of the ReactOS command line interpreter.\n"
1142 "CMD [/[C|K] command][/P][/Q][/T:bf]\n"
1144 " /C command Runs the specified command and terminates.\n"
1145 " /K command Runs the specified command and remains.\n"
1146 " /P CMD becomes permanent and runs autoexec.bat\n"
1147 " (cannot be terminated).\n"
1148 " /T:bf Sets the background/foreground color (see COLOR command)."));
1151 SetConsoleMode (hIn
, ENABLE_PROCESSED_INPUT
);
1153 #ifdef INCLUDE_CMD_CHDIR
1157 #ifdef FATURE_ALIASES
1163 for (i
= 1; i
< argc
; i
++)
1165 if (!_tcsicmp (argv
[i
], _T("/p")))
1167 if (!IsValidFileName (_T("\\autoexec.bat")))
1169 #ifdef INCLUDE_CMD_DATE
1170 cmd_date (_T(""), _T(""));
1172 #ifdef INCLUDE_CMD_TIME
1173 cmd_time (_T(""), _T(""));
1178 ParseCommandLine (_T("\\autoexec.bat"));
1182 else if (!_tcsicmp (argv
[i
], _T("/c")))
1184 /* This just runs a program and exits */
1188 _tcscpy (commandline
, argv
[i
]);
1191 _tcscat (commandline
, _T(" "));
1192 _tcscat (commandline
, argv
[i
]);
1195 ParseCommandLine(commandline
);
1196 ExitProcess (ProcessInput (TRUE
));
1203 else if (!_tcsicmp (argv
[i
], _T("/k")))
1205 /* This just runs a program and remains */
1209 _tcscpy (commandline
, argv
[i
]);
1212 _tcscat (commandline
, _T(" "));
1213 _tcscat (commandline
, argv
[i
]);
1216 ParseCommandLine(commandline
);
1219 #ifdef INCLUDE_CMD_COLOR
1220 else if (!_tcsnicmp (argv
[i
], _T("/t:"), 3))
1222 /* process /t (color) argument */
1223 wDefColor
= (WORD
)_tcstoul (&argv
[i
][3], NULL
, 16);
1225 SetScreenColor (wColor
, TRUE
);
1231 /* run cmdstart.bat */
1232 if (IsValidFileName (_T("cmdstart.bat")))
1234 ParseCommandLine (_T("cmdstart.bat"));
1236 else if (IsValidFileName (_T("\\cmdstart.bat")))
1238 ParseCommandLine (_T("\\cmdstart.bat"));
1243 /* try to run cmdstart.bat from install dir */
1246 _tcscpy (commandline
, argv
[0]);
1247 p
= _tcsrchr (commandline
, _T('\\')) + 1;
1248 _tcscpy (p
, _T("cmdstart.bat"));
1250 if (IsValidFileName (_T("commandline")))
1252 ConErrPrintf (_T("Running %s...\n", 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
[])
1283 /* run cmdexit.bat */
1284 if (IsValidFileName (_T("cmdexit.bat")))
1286 ConErrPrintf (_T("Running cmdexit.bat...\n"));
1287 ParseCommandLine (_T("cmdexit.bat"));
1289 else if (IsValidFileName (_T("\\cmdexit.bat")))
1291 ConErrPrintf (_T("Running \\cmdexit.bat...\n"));
1292 ParseCommandLine (_T("\\cmdexit.bat"));
1297 /* try to run cmdexit.bat from install dir */
1298 TCHAR commandline
[CMDLINE_LENGTH
];
1301 _tcscpy (commandline
, argv
[0]);
1302 p
= _tcsrchr (commandline
, _T('\\')) + 1;
1303 _tcscpy (p
, _T("cmdexit.bat"));
1305 if (IsValidFileName (_T("commandline")))
1307 ConErrPrintf (_T("Running %s...\n"), commandline
);
1308 ParseCommandLine (commandline
);
1313 #ifdef FEATURE_ALIASES
1317 #ifdef FEATURE_DIECTORY_STACK
1318 /* destroy directory stack */
1319 DestroyDirectoryStack ();
1322 #ifdef INCLUDE_CMD_CHDIR
1326 #ifdef FEATURE_HISTORY
1331 /* remove ctrl break handler */
1332 RemoveBreakHandler ();
1333 SetConsoleMode( GetStdHandle( STD_INPUT_HANDLE
),
1334 ENABLE_LINE_INPUT
| ENABLE_PROCESSED_INPUT
| ENABLE_ECHO_INPUT
);
1339 PWCHAR
* _CommandLineToArgvW(PWCHAR lpCmdLine
, int *pNumArgs
)
1341 PWCHAR
* argvw
= NULL
;
1342 PWCHAR ptr
= lpCmdLine
;
1349 while(lpCmdLine
&& *lpCmdLine
)
1351 while (iswspace(*lpCmdLine
)) lpCmdLine
++;
1354 if ((NumArgs
% 10)==0)
1356 PWCHAR
* old_argvw
= argvw
;
1357 argvw
= malloc((NumArgs
+ 10) * sizeof(PWCHAR
));
1358 memcpy(argvw
, old_argvw
, NumArgs
* sizeof(PWCHAR
));
1361 ptr
= wcschr(lpCmdLine
, L
' ');
1364 len
= ptr
- lpCmdLine
;
1368 len
= wcslen(lpCmdLine
);
1370 str
= malloc((len
+ 1) * sizeof(WCHAR
));
1371 memcpy(str
, lpCmdLine
, len
* sizeof(WCHAR
));
1378 *pNumArgs
= NumArgs
;
1390 int main (int argc
, char *argv
[])
1393 CONSOLE_SCREEN_BUFFER_INFO Info
;
1399 argv
= _CommandLineToArgvW(GetCommandLineW(), &argc
);
1401 argv
= CommandLineToArgvW(GetCommandLineW(), &argc
);
1407 hConsole
= CreateFile(_T("CONOUT$"), GENERIC_READ
|GENERIC_WRITE
,
1408 FILE_SHARE_READ
|FILE_SHARE_WRITE
, NULL
,
1409 OPEN_EXISTING
, 0, NULL
);
1410 if (GetConsoleScreenBufferInfo(hConsole
, &Info
) == FALSE
)
1412 ConOutFormatMessage(GetLastError());
1415 wColor
= Info
.wAttributes
;
1418 /* check switches on command-line */
1419 Initialize(argc
, argv
);
1421 /* call prompt routine */
1422 nExitCode
= ProcessInput(FALSE
);
1424 /* do the cleanup */
1425 Cleanup(argc
, argv
);