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.
137 #define NT_SUCCESS(StatCode) ((NTSTATUS)(StatCode) >= 0)
140 typedef NTSTATUS (STDCALL
*NtQueryInformationProcessProc
)(HANDLE
, PROCESSINFOCLASS
,
141 PVOID
, ULONG
, PULONG
);
142 typedef NTSTATUS (STDCALL
*NtReadVirtualMemoryProc
)(HANDLE
, PVOID
, PVOID
, ULONG
, PULONG
);
144 BOOL bExit
= FALSE
; /* indicates EXIT was typed */
145 BOOL bCanExit
= TRUE
; /* indicates if this shell is exitable */
146 BOOL bCtrlBreak
= FALSE
; /* Ctrl-Break or Ctrl-C hit */
147 BOOL bIgnoreEcho
= FALSE
; /* Ignore 'newline' before 'cls' */
148 INT nErrorLevel
= 0; /* Errorlevel of last launched external program */
149 BOOL bChildProcessRunning
= FALSE
;
150 DWORD dwChildProcessId
= 0;
156 static NtQueryInformationProcessProc NtQueryInformationProcessPtr
;
157 static NtReadVirtualMemoryProc NtReadVirtualMemoryPtr
;
158 static BOOL NtDllChecked
= FALSE
;
160 #ifdef INCLUDE_CMD_COLOR
161 WORD wColor
; /* current color */
162 WORD wDefColor
; /* default color */
166 * is character a delimeter when used on first word?
170 static BOOL
IsDelimiter (TCHAR c
)
172 return (c
== _T('/') || c
== _T('=') || c
== _T('\0') || _istspace (c
));
176 * Is a process a console process?
178 static BOOL
IsConsoleProcess(HANDLE Process
)
181 PROCESS_BASIC_INFORMATION Info
;
186 /* Some people like to run ReactOS cmd.exe on Win98, it helps in the
187 build process. So don't link implicitly against ntdll.dll, load it
188 dynamically instead */
192 NtDllModule
= LoadLibrary(_T("ntdll.dll"));
193 if (NULL
== NtDllModule
)
195 /* Probably non-WinNT system. Just wait for the commands
197 NtQueryInformationProcessPtr
= NULL
;
198 NtReadVirtualMemoryPtr
= NULL
;
201 NtQueryInformationProcessPtr
= (NtQueryInformationProcessProc
)
202 GetProcAddress(NtDllModule
, "NtQueryInformationProcess");
203 NtReadVirtualMemoryPtr
= (NtReadVirtualMemoryProc
)
204 GetProcAddress(NtDllModule
, "NtReadVirtualMemory");
207 if (NULL
== NtQueryInformationProcessPtr
|| NULL
== NtReadVirtualMemoryPtr
)
212 Status
= NtQueryInformationProcessPtr(Process
, ProcessBasicInformation
,
213 &Info
, sizeof(PROCESS_BASIC_INFORMATION
), NULL
);
214 if (! NT_SUCCESS(Status
))
217 DebugPrintf (_T("NtQueryInformationProcess failed with status %08x\n"), Status
);
221 Status
= NtReadVirtualMemoryPtr(Process
, Info
.PebBaseAddress
, &ProcessPeb
,
222 sizeof(PEB
), &BytesRead
);
223 if (! NT_SUCCESS(Status
) || sizeof(PEB
) != BytesRead
)
226 DebugPrintf (_T("Couldn't read virt mem status %08x bytes read %lu\n"), Status
, BytesRead
);
231 return IMAGE_SUBSYSTEM_WINDOWS_CUI
== ProcessPeb
.ImageSubSystem
;
237 #define SHELLEXECUTETEXT "ShellExecuteW"
239 #define SHELLEXECUTETEXT "ShellExecuteA"
242 typedef HINSTANCE (WINAPI
*MYEX
)(
246 LPCTSTR lpParameters
,
253 static BOOL
RunFile(LPTSTR filename
)
260 DebugPrintf (_T("RunFile(%s)\n"), filename
);
262 hShell32
= LoadLibrary(_T("SHELL32.DLL"));
266 DebugPrintf (_T("RunFile: couldn't load SHELL32.DLL!\n"));
271 hShExt
= (MYEX
)(FARPROC
)GetProcAddress(hShell32
, SHELLEXECUTETEXT
);
275 DebugPrintf (_T("RunFile: couldn't find ShellExecuteA/W in SHELL32.DLL!\n"));
277 FreeLibrary(hShell32
);
282 DebugPrintf (_T("RunFile: ShellExecuteA/W is at %x\n"), hShExt
);
285 ret
= (hShExt
)(NULL
, _T("open"), filename
, NULL
, NULL
, SW_SHOWNORMAL
);
288 DebugPrintf (_T("RunFile: ShellExecuteA/W returned %d\n"), (DWORD
)ret
);
291 FreeLibrary(hShell32
);
292 return (((DWORD
)ret
) > 32);
298 * This command (in first) was not found in the command table
300 * first - first word on command line
301 * rest - rest of command line
305 Execute (LPTSTR full
, LPTSTR first
, LPTSTR rest
)
307 TCHAR szFullName
[MAX_PATH
];
309 TCHAR szWindowTitle
[MAX_PATH
];
311 DWORD dwExitCode
= 0;
314 DebugPrintf (_T("Execute: \'%s\' \'%s\'\n"), first
, rest
);
317 /* check for a drive change */
318 if ((_istalpha (first
[0])) && (!_tcscmp (first
+ 1, _T(":"))))
321 if (!SetCurrentDirectory(first
))
322 /* Guess they changed disc or something, handle that gracefully and get to root */
329 working
= SetCurrentDirectory(str
);
332 if (!working
) ConErrPuts (INVALIDDRIVE
);
337 /* get the PATH environment variable and parse it */
338 /* search the PATH environment variable for the binary */
339 if (!SearchForExecutable (first
, szFullName
))
341 error_bad_command ();
346 GetConsoleTitle (szWindowTitle
, MAX_PATH
);
349 /* check if this is a .BAT or .CMD file */
350 if (!_tcsicmp (_tcsrchr (szFullName
, _T('.')), _T(".bat")) ||
351 !_tcsicmp (_tcsrchr (szFullName
, _T('.')), _T(".cmd")))
354 DebugPrintf (_T("[BATCH: %s %s]\n"), szFullName
, rest
);
356 Batch (szFullName
, first
, rest
);
360 /* exec the program */
361 PROCESS_INFORMATION prci
;
365 DebugPrintf (_T("[EXEC: %s %s]\n"), full
, rest
);
367 /* build command line for CreateProcess() */
369 /* fill startup info */
370 memset (&stui
, 0, sizeof (STARTUPINFO
));
371 stui
.cb
= sizeof (STARTUPINFO
);
372 stui
.dwFlags
= STARTF_USESHOWWINDOW
;
373 stui
.wShowWindow
= SW_SHOWDEFAULT
;
375 // return console to standard mode
376 SetConsoleMode (GetStdHandle(STD_INPUT_HANDLE
),
377 ENABLE_LINE_INPUT
| ENABLE_PROCESSED_INPUT
| ENABLE_ECHO_INPUT
);
379 if (CreateProcess (szFullName
,
384 CREATE_NEW_PROCESS_GROUP
,
390 if (IsConsoleProcess(prci
.hProcess
))
392 /* FIXME: Protect this with critical section */
393 bChildProcessRunning
= TRUE
;
394 dwChildProcessId
= prci
.dwProcessId
;
396 WaitForSingleObject (prci
.hProcess
, INFINITE
);
398 /* FIXME: Protect this with critical section */
399 bChildProcessRunning
= FALSE
;
401 GetExitCodeProcess (prci
.hProcess
, &dwExitCode
);
402 nErrorLevel
= (INT
)dwExitCode
;
404 CloseHandle (prci
.hThread
);
405 CloseHandle (prci
.hProcess
);
410 DebugPrintf (_T("[ShellExecute: %s]\n"), full
);
412 // See if we can run this with ShellExecute() ie myfile.xls
416 DebugPrintf (_T("[ShellExecute failed!: %s]\n"), full
);
418 error_bad_command ();
421 // restore console mode
422 SetConsoleMode( GetStdHandle( STD_INPUT_HANDLE
),
423 ENABLE_PROCESSED_INPUT
);
427 SetConsoleTitle (szWindowTitle
);
433 * look through the internal commands and determine whether or not this
434 * command is one of them. If it is, call the command. If not, call
435 * execute to run it as an external program.
437 * line - the command line of the program to run
442 DoCommand (LPTSTR line
)
444 TCHAR com
[CMDLINE_LENGTH
]; /* the first word in the command */
447 LPTSTR rest
; /* pointer to the rest of the command line */
452 DebugPrintf (_T("DoCommand: (\'%s\')\n"), line
);
455 /* Skip over initial white space */
456 while (_istspace (*line
))
462 /* Anything to do ? */
465 if (*rest
== _T('"'))
467 /* treat quoted words specially */
471 while(*rest
!= _T('\0') && *rest
!= _T('"'))
472 *cp
++ = _totlower (*rest
++);
473 if (*rest
== _T('"'))
478 while (!IsDelimiter (*rest
))
479 *cp
++ = _totlower (*rest
++);
483 /* Terminate first word */
486 /* commands are limited to MAX_PATH */
487 if(_tcslen(com
) > MAX_PATH
)
493 /* Skip over whitespace to rest of line */
494 while (_istspace (*rest
))
497 /* Scan internal command table */
498 for (cmdptr
= cmds
;; cmdptr
++)
500 /* If end of table execute ext cmd */
501 if (cmdptr
->name
== NULL
)
503 Execute (line
, com
, rest
);
507 if (!_tcscmp (com
, cmdptr
->name
))
509 cmdptr
->func (com
, rest
);
513 /* The following code handles the case of commands like CD which
514 * are recognised even when the command name and parameter are
515 * not space separated.
521 /* Get length of command name */
522 cl
= _tcslen (cmdptr
->name
);
524 if ((cmdptr
->flags
& CMD_SPECIAL
) &&
525 (!_tcsncmp (cmdptr
->name
, com
, cl
)) &&
526 (_tcschr (_T("\\.-"), *(com
+ cl
))))
528 /* OK its one of the specials...*/
530 /* Terminate first word properly */
533 /* Call with new rest */
534 cmdptr
->func (com
, cstart
+ cl
);
543 * process the command line and execute the appropriate functions
544 * full input/output redirection and piping are supported
547 VOID
ParseCommandLine (LPTSTR cmd
)
549 TCHAR cmdline
[CMDLINE_LENGTH
];
551 #ifdef FEATURE_REDIRECTION
552 TCHAR in
[CMDLINE_LENGTH
] = _T("");
553 TCHAR out
[CMDLINE_LENGTH
] = _T("");
554 TCHAR err
[CMDLINE_LENGTH
] = _T("");
555 TCHAR szTempPath
[MAX_PATH
] = _T(".\\");
556 TCHAR szFileName
[2][MAX_PATH
] = {_T(""), _T("")};
557 HANDLE hFile
[2] = {INVALID_HANDLE_VALUE
, INVALID_HANDLE_VALUE
};
567 #endif /* FEATURE_REDIRECTION */
569 _tcscpy (cmdline
, cmd
);
573 DebugPrintf (_T("ParseCommandLine: (\'%s\')\n"), s
);
576 #ifdef FEATURE_ALIASES
577 /* expand all aliases */
578 ExpandAlias (s
, CMDLINE_LENGTH
);
579 #endif /* FEATURE_ALIAS */
581 #ifdef FEATURE_REDIRECTION
582 /* find the temp path to store temporary files */
583 Length
= GetTempPath (MAX_PATH
, szTempPath
);
584 if (Length
> 0 && Length
< MAX_PATH
)
586 Attributes
= GetFileAttributes(szTempPath
);
587 if (Attributes
== 0xffffffff ||
588 !(Attributes
& FILE_ATTRIBUTE_DIRECTORY
))
593 if (Length
== 0 || Length
>= MAX_PATH
)
595 _tcscpy(szTempPath
, _T(".\\"));
597 if (szTempPath
[_tcslen (szTempPath
) - 1] != _T('\\'))
598 _tcscat (szTempPath
, _T("\\"));
600 /* get the redirections from the command line */
601 num
= GetRedirection (s
, in
, out
, err
, &nRedirFlags
);
603 /* more efficient, but do we really need to do this? */
604 for (t
= in
; _istspace (*t
); t
++)
608 for (t
= out
; _istspace (*t
); t
++)
612 for (t
= err
; _istspace (*t
); t
++)
616 /* Set up the initial conditions ... */
617 /* preserve STDIN, STDOUT and STDERR handles */
618 hOldConIn
= GetStdHandle (STD_INPUT_HANDLE
);
619 hOldConOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
620 hOldConErr
= GetStdHandle (STD_ERROR_HANDLE
);
626 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
628 hFile
= CreateFile (in
, GENERIC_READ
, FILE_SHARE_READ
, &sa
, OPEN_EXISTING
,
629 FILE_ATTRIBUTE_NORMAL
, NULL
);
630 if (hFile
== INVALID_HANDLE_VALUE
)
632 ConErrPrintf (_T("Can't redirect input from file %s\n"), in
);
636 if (!SetStdHandle (STD_INPUT_HANDLE
, hFile
))
638 ConErrPrintf (_T("Can't redirect input from file %s\n"), in
);
642 DebugPrintf (_T("Input redirected from: %s\n"), in
);
646 /* Now do all but the last pipe command */
647 *szFileName
[0] = _T('\0');
648 hFile
[0] = INVALID_HANDLE_VALUE
;
652 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
654 /* Create unique temporary file name */
655 GetTempFileName (szTempPath
, _T("CMD"), 0, szFileName
[1]);
657 /* Set current stdout to temporary file */
658 hFile
[1] = CreateFile (szFileName
[1], GENERIC_WRITE
, 0, &sa
,
659 TRUNCATE_EXISTING
, FILE_ATTRIBUTE_TEMPORARY
, NULL
);
661 if (hFile
[1] == INVALID_HANDLE_VALUE
){
662 ConErrPrintf (_T("Error creating temporary file for pipe data\n"));
666 SetStdHandle (STD_OUTPUT_HANDLE
, hFile
[1]);
670 /* close stdout file */
671 SetStdHandle (STD_OUTPUT_HANDLE
, hOldConOut
);
672 if ((hFile
[1] != INVALID_HANDLE_VALUE
) && (hFile
[1] != hOldConOut
))
674 CloseHandle (hFile
[1]);
675 hFile
[1] = INVALID_HANDLE_VALUE
;
678 /* close old stdin file */
679 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
680 if ((hFile
[0] != INVALID_HANDLE_VALUE
) && (hFile
[0] != hOldConIn
))
682 /* delete old stdin file, if it is a real file */
683 CloseHandle (hFile
[0]);
684 hFile
[0] = INVALID_HANDLE_VALUE
;
685 DeleteFile (szFileName
[0]);
686 *szFileName
[0] = _T('\0');
689 /* copy stdout file name to stdin file name */
690 _tcscpy (szFileName
[0], szFileName
[1]);
691 *szFileName
[1] = _T('\0');
693 /* open new stdin file */
694 hFile
[0] = CreateFile (szFileName
[0], GENERIC_READ
, 0, &sa
,
695 OPEN_EXISTING
, FILE_ATTRIBUTE_TEMPORARY
, NULL
);
696 SetStdHandle (STD_INPUT_HANDLE
, hFile
[0]);
698 s
= s
+ _tcslen (s
) + 1;
701 /* Now set up the end conditions... */
702 /* redirect STDOUT */
705 /* Final output to here */
707 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
709 hFile
= CreateFile (out
, GENERIC_WRITE
, FILE_SHARE_READ
, &sa
,
710 (nRedirFlags
& OUTPUT_APPEND
) ? OPEN_ALWAYS
: CREATE_ALWAYS
,
711 FILE_ATTRIBUTE_NORMAL
, NULL
);
712 if (hFile
== INVALID_HANDLE_VALUE
)
714 ConErrPrintf (_T("Can't redirect to file %s\n"), out
);
718 if (!SetStdHandle (STD_OUTPUT_HANDLE
, hFile
))
720 ConErrPrintf (_T("Can't redirect to file %s\n"), out
);
724 if (nRedirFlags
& OUTPUT_APPEND
)
728 if (GetFileType (hFile
) == FILE_TYPE_DISK
)
729 SetFilePointer (hFile
, 0, &lHighPos
, FILE_END
);
732 DebugPrintf (_T("Output redirected to: %s\n"), out
);
735 else if (hOldConOut
!= INVALID_HANDLE_VALUE
)
737 /* Restore original stdout */
738 HANDLE hOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
739 SetStdHandle (STD_OUTPUT_HANDLE
, hOldConOut
);
740 if (hOldConOut
!= hOut
)
742 hOldConOut
= INVALID_HANDLE_VALUE
;
745 /* redirect STDERR */
748 /* Final output to here */
750 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
752 if (!_tcscmp (err
, out
))
755 DebugPrintf (_T("Stdout and stderr will use the same file!!\n"));
757 DuplicateHandle (GetCurrentProcess (),
758 GetStdHandle (STD_OUTPUT_HANDLE
),
759 GetCurrentProcess (),
760 &hFile
, 0, TRUE
, DUPLICATE_SAME_ACCESS
);
764 hFile
= CreateFile (err
,
768 (nRedirFlags
& ERROR_APPEND
) ? OPEN_ALWAYS
: CREATE_ALWAYS
,
769 FILE_ATTRIBUTE_NORMAL
,
771 if (hFile
== INVALID_HANDLE_VALUE
)
773 ConErrPrintf (_T("Can't redirect to file %s\n"), err
);
777 if (!SetStdHandle (STD_ERROR_HANDLE
, hFile
))
779 ConErrPrintf (_T("Can't redirect to file %s\n"), err
);
783 if (nRedirFlags
& ERROR_APPEND
)
787 if (GetFileType (hFile
) == FILE_TYPE_DISK
)
788 SetFilePointer (hFile
, 0, &lHighPos
, FILE_END
);
791 DebugPrintf (_T("Error redirected to: %s\n"), err
);
794 else if (hOldConErr
!= INVALID_HANDLE_VALUE
)
796 /* Restore original stderr */
797 HANDLE hErr
= GetStdHandle (STD_ERROR_HANDLE
);
798 SetStdHandle (STD_ERROR_HANDLE
, hOldConErr
);
799 if (hOldConErr
!= hErr
)
801 hOldConErr
= INVALID_HANDLE_VALUE
;
805 /* process final command */
808 #ifdef FEATURE_REDIRECTION
809 /* close old stdin file */
810 #if 0 /* buggy implementation */
811 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
812 if ((hFile
[0] != INVALID_HANDLE_VALUE
) &&
813 (hFile
[0] != hOldConIn
))
815 /* delete old stdin file, if it is a real file */
816 CloseHandle (hFile
[0]);
817 hFile
[0] = INVALID_HANDLE_VALUE
;
818 DeleteFile (szFileName
[0]);
819 *szFileName
[0] = _T('\0');
822 /* Restore original STDIN */
823 if (hOldConIn
!= INVALID_HANDLE_VALUE
)
825 HANDLE hIn
= GetStdHandle (STD_INPUT_HANDLE
);
826 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
827 if (hOldConIn
!= hIn
)
829 hOldConIn
= INVALID_HANDLE_VALUE
;
834 DebugPrintf (_T("Can't restore STDIN! Is invalid!!\n"), out
);
837 #endif /* buggy implementation */
840 if (hOldConIn
!= INVALID_HANDLE_VALUE
)
842 HANDLE hIn
= GetStdHandle (STD_INPUT_HANDLE
);
843 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
844 if (hIn
== INVALID_HANDLE_VALUE
)
847 DebugPrintf (_T("Previous STDIN is invalid!!\n"));
852 if (GetFileType (hIn
) == FILE_TYPE_DISK
)
856 CloseHandle (hFile
[0]);
857 hFile
[0] = INVALID_HANDLE_VALUE
;
858 DeleteFile (szFileName
[0]);
859 *szFileName
[0] = _T('\0');
864 DebugPrintf (_T("hFile[0] and hIn dont match!!!\n"));
872 /* Restore original STDOUT */
873 if (hOldConOut
!= INVALID_HANDLE_VALUE
)
875 HANDLE hOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
876 SetStdHandle (STD_OUTPUT_HANDLE
, hOldConOut
);
877 if (hOldConOut
!= hOut
)
879 hOldConOut
= INVALID_HANDLE_VALUE
;
882 /* Restore original STDERR */
883 if (hOldConErr
!= INVALID_HANDLE_VALUE
)
885 HANDLE hErr
= GetStdHandle (STD_ERROR_HANDLE
);
886 SetStdHandle (STD_ERROR_HANDLE
, hOldConErr
);
887 if (hOldConErr
!= hErr
)
889 hOldConErr
= INVALID_HANDLE_VALUE
;
891 #endif /* FEATURE_REDIRECTION */
896 * do the prompt/input/process loop
901 ProcessInput (BOOL bFlag
)
903 TCHAR commandline
[CMDLINE_LENGTH
];
904 TCHAR readline
[CMDLINE_LENGTH
];
912 /* if no batch input then... */
913 if (!(ip
= ReadBatchLine (&bEchoThisLine
)))
918 ReadCommand (readline
, CMDLINE_LENGTH
);
920 bEchoThisLine
= FALSE
;
944 if ((tp
= FindArg (*ip
- _T('0'))))
946 cp
= _stpcpy (cp
, tp
);
954 cp
+= _stprintf (cp
, _T("%u"), nErrorLevel
);
959 tp
= _tcschr(ip
, _T('%'));
961 (tp
<= _tcschr(ip
, _T(' ')) - 1))
966 /* FIXME: This is just a quick hack!! */
967 /* Do a proper memory allocation!! */
968 if (GetEnvironmentVariable (ip
, evar
, 512))
969 cp
= _stpcpy (cp
, evar
);
989 /* strip trailing spaces */
990 while ((--cp
>= commandline
) && _istspace (*cp
));
992 *(cp
+ 1) = _T('\0');
995 /* Echo batch file line */
999 ConOutPuts (commandline
);
1004 ParseCommandLine (commandline
);
1005 if (bEcho
&& !bIgnoreEcho
)
1007 bIgnoreEcho
= FALSE
;
1010 while (!bCanExit
|| !bExit
);
1017 * control-break handler.
1019 BOOL WINAPI
BreakHandler (DWORD dwCtrlType
)
1021 if ((dwCtrlType
!= CTRL_C_EVENT
) &&
1022 (dwCtrlType
!= CTRL_BREAK_EVENT
))
1025 if (bChildProcessRunning
== TRUE
)
1027 GenerateConsoleCtrlEvent (CTRL_C_EVENT
,
1032 /* FIXME: Handle batch files */
1034 /* FIXME: Print "^C" */
1041 VOID
AddBreakHandler (VOID
)
1043 SetConsoleCtrlHandler ((PHANDLER_ROUTINE
)BreakHandler
, TRUE
);
1047 VOID
RemoveBreakHandler (VOID
)
1049 SetConsoleCtrlHandler ((PHANDLER_ROUTINE
)BreakHandler
, FALSE
);
1054 * show commands and options that are available.
1061 /* print command list */
1062 ConOutPrintf (_T("\nInternal commands available:\n"));
1063 PrintCommandList ();
1065 /* print feature list */
1066 ConOutPuts (_T("\nFeatures available:"));
1067 #ifdef FEATURE_ALIASES
1068 ConOutPuts (_T(" [aliases]"));
1070 #ifdef FEATURE_HISTORY
1071 ConOutPuts (_T(" [history]"));
1073 #ifdef FEATURE_UNIX_FILENAME_COMPLETION
1074 ConOutPuts (_T(" [unix filename completion]"));
1076 #ifdef FEATURE_DIRECTORY_STACK
1077 ConOutPuts (_T(" [directory stack]"));
1079 #ifdef FEATURE_REDIRECTION
1080 ConOutPuts (_T(" [redirections and piping]"));
1082 ConOutChar (_T('\n'));
1087 * set up global initializations and process parameters
1089 * argc - number of parameters to command.com
1090 * argv - command-line parameters
1094 Initialize (int argc
, TCHAR
* argv
[])
1096 TCHAR commandline
[CMDLINE_LENGTH
];
1097 TCHAR ModuleName
[_MAX_PATH
+ 1];
1100 //TCHAR *ptr, *cmdLine;
1106 DebugPrintf (_T("[command args:\n"));
1107 for (x
= 0; x
< argc
; x
++)
1109 DebugPrintf (_T("%d. %s\n"), x
, argv
[x
]);
1111 DebugPrintf (_T("]\n"));
1114 /* get version information */
1115 osvi
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
1116 GetVersionEx (&osvi
);
1120 /* get default input and output console handles */
1121 hOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
1122 hIn
= GetStdHandle (STD_INPUT_HANDLE
);
1125 if (argc
>= 2 && !_tcsncmp (argv
[1], _T("/?"), 2))
1127 ConOutPuts (_T("Starts a new instance of the ReactOS command line interpreter.\n"
1129 "CMD [/[C|K] command][/P][/Q][/T:bf]\n"
1131 " /C command Runs the specified command and terminates.\n"
1132 " /K command Runs the specified command and remains.\n"
1133 " /P CMD becomes permanent and runs autoexec.bat\n"
1134 " (cannot be terminated).\n"
1135 " /T:bf Sets the background/foreground color (see COLOR command)."));
1138 SetConsoleMode (hIn
, ENABLE_PROCESSED_INPUT
);
1140 #ifdef INCLUDE_CMD_CHDIR
1144 #ifdef FATURE_ALIASES
1150 for (i
= 1; i
< argc
; i
++)
1152 if (!_tcsicmp (argv
[i
], _T("/p")))
1154 if (!IsExistingFile (_T("\\autoexec.bat")))
1156 #ifdef INCLUDE_CMD_DATE
1157 cmd_date (_T(""), _T(""));
1159 #ifdef INCLUDE_CMD_TIME
1160 cmd_time (_T(""), _T(""));
1165 ParseCommandLine (_T("\\autoexec.bat"));
1169 else if (!_tcsicmp (argv
[i
], _T("/c")))
1171 /* This just runs a program and exits */
1175 _tcscpy (commandline
, argv
[i
]);
1178 _tcscat (commandline
, _T(" "));
1179 _tcscat (commandline
, argv
[i
]);
1182 ParseCommandLine(commandline
);
1183 ExitProcess (ProcessInput (TRUE
));
1190 else if (!_tcsicmp (argv
[i
], _T("/k")))
1192 /* This just runs a program and remains */
1196 _tcscpy (commandline
, argv
[i
]);
1199 _tcscat (commandline
, _T(" "));
1200 _tcscat (commandline
, argv
[i
]);
1203 ParseCommandLine(commandline
);
1206 #ifdef INCLUDE_CMD_COLOR
1207 else if (!_tcsnicmp (argv
[i
], _T("/t:"), 3))
1209 /* process /t (color) argument */
1210 wDefColor
= (WORD
)_tcstoul (&argv
[i
][3], NULL
, 16);
1212 SetScreenColor (wColor
, TRUE
);
1218 /* run cmdstart.bat */
1219 if (IsExistingFile (_T("cmdstart.bat")))
1221 ParseCommandLine (_T("cmdstart.bat"));
1223 else if (IsExistingFile (_T("\\cmdstart.bat")))
1225 ParseCommandLine (_T("\\cmdstart.bat"));
1230 /* try to run cmdstart.bat from install dir */
1233 _tcscpy (commandline
, argv
[0]);
1234 p
= _tcsrchr (commandline
, _T('\\')) + 1;
1235 _tcscpy (p
, _T("cmdstart.bat"));
1237 if (IsExistingFile (_T("commandline")))
1239 ConErrPrintf (_T("Running %s...\n", commandline
));
1240 ParseCommandLine (commandline
);
1245 #ifdef FEATURE_DIR_STACK
1246 /* initialize directory stack */
1247 InitDirectoryStack ();
1251 #ifdef FEATURE_HISTORY
1252 /*initialize history*/
1256 /* Set COMSPEC environment variable */
1257 if (0 != GetModuleFileName (NULL
, ModuleName
, _MAX_PATH
+ 1))
1259 ModuleName
[_MAX_PATH
] = _T('\0');
1260 SetEnvironmentVariable (_T("COMSPEC"), ModuleName
);
1263 /* add ctrl break handler */
1268 static VOID
Cleanup (int argc
, TCHAR
*argv
[])
1270 /* run cmdexit.bat */
1271 if (IsExistingFile (_T("cmdexit.bat")))
1273 ConErrPrintf (_T("Running cmdexit.bat...\n"));
1274 ParseCommandLine (_T("cmdexit.bat"));
1276 else if (IsExistingFile (_T("\\cmdexit.bat")))
1278 ConErrPrintf (_T("Running \\cmdexit.bat...\n"));
1279 ParseCommandLine (_T("\\cmdexit.bat"));
1284 /* try to run cmdexit.bat from install dir */
1285 TCHAR commandline
[CMDLINE_LENGTH
];
1288 _tcscpy (commandline
, argv
[0]);
1289 p
= _tcsrchr (commandline
, _T('\\')) + 1;
1290 _tcscpy (p
, _T("cmdexit.bat"));
1292 if (IsExistingFile (_T("commandline")))
1294 ConErrPrintf (_T("Running %s...\n"), commandline
);
1295 ParseCommandLine (commandline
);
1300 #ifdef FEATURE_ALIASES
1304 #ifdef FEATURE_DIECTORY_STACK
1305 /* destroy directory stack */
1306 DestroyDirectoryStack ();
1309 #ifdef INCLUDE_CMD_CHDIR
1313 #ifdef FEATURE_HISTORY
1318 /* remove ctrl break handler */
1319 RemoveBreakHandler ();
1320 SetConsoleMode( GetStdHandle( STD_INPUT_HANDLE
),
1321 ENABLE_LINE_INPUT
| ENABLE_PROCESSED_INPUT
| ENABLE_ECHO_INPUT
);
1326 PWCHAR
* _CommandLineToArgvW(PWCHAR lpCmdLine
, int *pNumArgs
)
1328 PWCHAR
* argvw
= NULL
;
1329 PWCHAR ptr
= lpCmdLine
;
1336 while(lpCmdLine
&& *lpCmdLine
)
1338 while (iswspace(*lpCmdLine
)) lpCmdLine
++;
1341 if ((NumArgs
% 10)==0)
1343 PWCHAR
* old_argvw
= argvw
;
1344 argvw
= malloc((NumArgs
+ 10) * sizeof(PWCHAR
));
1345 memcpy(argvw
, old_argvw
, NumArgs
* sizeof(PWCHAR
));
1348 ptr
= wcschr(lpCmdLine
, L
' ');
1351 len
= ptr
- lpCmdLine
;
1355 len
= wcslen(lpCmdLine
);
1357 str
= malloc((len
+ 1) * sizeof(WCHAR
));
1358 memcpy(str
, lpCmdLine
, len
* sizeof(WCHAR
));
1365 *pNumArgs
= NumArgs
;
1377 int main (int argc
, char *argv
[])
1380 CONSOLE_SCREEN_BUFFER_INFO Info
;
1386 argv
= _CommandLineToArgvW(GetCommandLineW(), &argc
);
1388 argv
= CommandLineToArgvW(GetCommandLineW(), &argc
);
1394 hConsole
= CreateFile(_T("CONOUT$"), GENERIC_READ
|GENERIC_WRITE
,
1395 FILE_SHARE_READ
|FILE_SHARE_WRITE
, NULL
,
1396 OPEN_EXISTING
, 0, NULL
);
1397 if (GetConsoleScreenBufferInfo(hConsole
, &Info
) == FALSE
)
1399 ConOutFormatMessage(GetLastError());
1402 wColor
= Info
.wAttributes
;
1405 /* check switches on command-line */
1406 Initialize(argc
, argv
);
1408 /* call prompt routine */
1409 nExitCode
= ProcessInput(FALSE
);
1411 /* do the cleanup */
1412 Cleanup(argc
, argv
);