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
135 * 06-May-2005 (Klemens Friedl <frik85@gmail.com>)
136 * Add 'help' command (list all commands plus description)
138 * 06-jul-2005 (Magnus Olsen <magnus@greatlord.com>)
139 * translate '%errorlevel%' to the internal value.
140 * Add proper memmory alloc ProcessInput, the error
141 * handling for memmory handling need to be improve
145 #include "resource.h"
148 #define NT_SUCCESS(StatCode) ((NTSTATUS)(StatCode) >= 0)
151 typedef NTSTATUS (WINAPI
*NtQueryInformationProcessProc
)(HANDLE
, PROCESSINFOCLASS
,
152 PVOID
, ULONG
, PULONG
);
153 typedef NTSTATUS (WINAPI
*NtReadVirtualMemoryProc
)(HANDLE
, PVOID
, PVOID
, ULONG
, PULONG
);
155 BOOL bExit
= FALSE
; /* indicates EXIT was typed */
156 BOOL bCanExit
= TRUE
; /* indicates if this shell is exitable */
157 BOOL bCtrlBreak
= FALSE
; /* Ctrl-Break or Ctrl-C hit */
158 BOOL bIgnoreEcho
= FALSE
; /* Ignore 'newline' before 'cls' */
159 INT nErrorLevel
= 0; /* Errorlevel of last launched external program */
160 BOOL bChildProcessRunning
= FALSE
;
161 DWORD dwChildProcessId
= 0;
166 HANDLE CMD_ModuleHandle
;
169 static NtQueryInformationProcessProc NtQueryInformationProcessPtr
= NULL
;
170 static NtReadVirtualMemoryProc NtReadVirtualMemoryPtr
= NULL
;
172 #ifdef INCLUDE_CMD_COLOR
173 WORD wColor
; /* current color */
174 WORD wDefColor
; /* default color */
178 * is character a delimeter when used on first word?
182 static BOOL
IsDelimiter (TCHAR c
)
184 return (c
== _T('/') || c
== _T('=') || c
== _T('\0') || _istspace (c
));
188 * Is a process a console process?
190 static BOOL
IsConsoleProcess(HANDLE Process
)
193 PROCESS_BASIC_INFORMATION Info
;
197 if (NULL
== NtQueryInformationProcessPtr
|| NULL
== NtReadVirtualMemoryPtr
)
202 Status
= NtQueryInformationProcessPtr (
203 Process
, ProcessBasicInformation
,
204 &Info
, sizeof(PROCESS_BASIC_INFORMATION
), NULL
);
205 if (! NT_SUCCESS(Status
))
208 DebugPrintf (_T("NtQueryInformationProcess failed with status %08x\n"), Status
);
212 Status
= NtReadVirtualMemoryPtr (
213 Process
, Info
.PebBaseAddress
, &ProcessPeb
,
214 sizeof(PEB
), &BytesRead
);
215 if (! NT_SUCCESS(Status
) || sizeof(PEB
) != BytesRead
)
218 DebugPrintf (_T("Couldn't read virt mem status %08x bytes read %lu\n"), Status
, BytesRead
);
223 return IMAGE_SUBSYSTEM_WINDOWS_CUI
== ProcessPeb
.ImageSubSystem
;
229 #define SHELLEXECUTETEXT "ShellExecuteW"
231 #define SHELLEXECUTETEXT "ShellExecuteA"
234 typedef HINSTANCE (WINAPI
*MYEX
)(
238 LPCTSTR lpParameters
,
245 static BOOL
RunFile(LPTSTR filename
)
252 DebugPrintf (_T("RunFile(%s)\n"), filename
);
254 hShell32
= LoadLibrary(_T("SHELL32.DLL"));
258 DebugPrintf (_T("RunFile: couldn't load SHELL32.DLL!\n"));
263 hShExt
= (MYEX
)(FARPROC
)GetProcAddress(hShell32
, SHELLEXECUTETEXT
);
267 DebugPrintf (_T("RunFile: couldn't find ShellExecuteA/W in SHELL32.DLL!\n"));
269 FreeLibrary(hShell32
);
274 DebugPrintf (_T("RunFile: ShellExecuteA/W is at %x\n"), hShExt
);
277 ret
= (hShExt
)(NULL
, _T("open"), filename
, NULL
, NULL
, SW_SHOWNORMAL
);
280 DebugPrintf (_T("RunFile: ShellExecuteA/W returned %d\n"), (DWORD
)ret
);
283 FreeLibrary(hShell32
);
284 return (((DWORD
)ret
) > 32);
290 * This command (in first) was not found in the command table
292 * Full - whole command line
293 * First - first word on command line
294 * Rest - rest of command line
298 Execute (LPTSTR Full
, LPTSTR First
, LPTSTR Rest
)
300 TCHAR
*szFullName
=NULL
;
305 TCHAR szWindowTitle
[MAX_PATH
];
306 DWORD dwExitCode
= 0;
309 DebugPrintf (_T("Execute: \'%s\' \'%s\'\n"), first
, rest
);
312 /* we need biger buffer that First, Rest, Full are already
313 need rewrite some code to use realloc when it need instead
314 of add 512bytes extra */
316 first
= malloc ( (_tcslen(First
) + 512) * sizeof(TCHAR
));
319 error_out_of_memory();
323 rest
= malloc ( (_tcslen(Rest
) + 512) * sizeof(TCHAR
));
327 error_out_of_memory();
331 full
= malloc ( (_tcslen(Full
) + 512) * sizeof(TCHAR
));
336 error_out_of_memory();
340 szFullName
= malloc ( (_tcslen(Full
) + 512) * sizeof(TCHAR
));
346 error_out_of_memory();
351 /* Though it was already parsed once, we have a different set of rules
352 for parsing before we pass to CreateProccess */
353 if(!_tcschr(Full
,_T('\"')))
355 _tcscpy(first
,First
);
362 BOOL bInside
= FALSE
;
367 /* find the end of the command and start of the args */
368 for(i
= 0; i
< _tcslen(first
); i
++)
370 if(!_tcsncmp(&first
[i
], _T("\""), 1))
372 if(!_tcsncmp(&first
[i
], _T(" "), 1) && !bInside
)
374 _tcscpy(rest
,&first
[i
]);
381 /* remove any slashes */
382 while(i
< _tcslen(first
))
384 if(first
[i
] == _T('\"'))
385 memmove(&first
[i
],&first
[i
+ 1], _tcslen(&first
[i
]) * sizeof(TCHAR
));
389 /* Drop quotes around it just in case there is a space */
390 _tcscpy(full
,_T("\""));
392 _tcscat(full
,_T("\" "));
396 /* check for a drive change */
397 if ((_istalpha (first
[0])) && (!_tcscmp (first
+ 1, _T(":"))))
400 if (!SetCurrentDirectory(first
))
401 /* Guess they changed disc or something, handle that gracefully and get to root */
408 working
= SetCurrentDirectory(str
);
411 if (!working
) ConErrResPuts (STRING_FREE_ERROR1
);
421 /* get the PATH environment variable and parse it */
422 /* search the PATH environment variable for the binary */
423 if (!SearchForExecutable (first
, szFullName
))
425 if (!SearchForExecutable (full
, szFullName
))
427 error_bad_command ();
437 GetConsoleTitle (szWindowTitle
, MAX_PATH
);
439 /* check if this is a .BAT or .CMD file */
440 dot
= _tcsrchr (szFullName
, _T('.'));
441 if (dot
&& (!_tcsicmp (dot
, _T(".bat")) || !_tcsicmp (dot
, _T(".cmd"))))
444 DebugPrintf (_T("[BATCH: %s %s]\n"), szFullName
, rest
);
446 Batch (szFullName
, first
, rest
);
450 /* exec the program */
451 PROCESS_INFORMATION prci
;
455 DebugPrintf (_T("[EXEC: %s %s]\n"), full
, rest
);
457 /* build command line for CreateProcess() */
459 /* fill startup info */
460 memset (&stui
, 0, sizeof (STARTUPINFO
));
461 stui
.cb
= sizeof (STARTUPINFO
);
462 stui
.dwFlags
= STARTF_USESHOWWINDOW
;
463 stui
.wShowWindow
= SW_SHOWDEFAULT
;
465 // return console to standard mode
466 SetConsoleMode (GetStdHandle(STD_INPUT_HANDLE
),
467 ENABLE_LINE_INPUT
| ENABLE_PROCESSED_INPUT
| ENABLE_ECHO_INPUT
);
469 if (CreateProcess (szFullName
,
474 CREATE_NEW_PROCESS_GROUP
,
480 if (IsConsoleProcess(prci
.hProcess
))
482 /* FIXME: Protect this with critical section */
483 bChildProcessRunning
= TRUE
;
484 dwChildProcessId
= prci
.dwProcessId
;
486 WaitForSingleObject (prci
.hProcess
, INFINITE
);
488 /* FIXME: Protect this with critical section */
489 bChildProcessRunning
= FALSE
;
491 GetExitCodeProcess (prci
.hProcess
, &dwExitCode
);
492 nErrorLevel
= (INT
)dwExitCode
;
494 CloseHandle (prci
.hThread
);
495 CloseHandle (prci
.hProcess
);
500 DebugPrintf (_T("[ShellExecute: %s]\n"), full
);
502 // See if we can run this with ShellExecute() ie myfile.xls
506 DebugPrintf (_T("[ShellExecute failed!: %s]\n"), full
);
508 error_bad_command ();
511 // restore console mode
513 GetStdHandle( STD_INPUT_HANDLE
),
514 ENABLE_PROCESSED_INPUT
);
517 /* Get code page if it has been change */
518 InputCodePage
= GetConsoleCP();
519 OutputCodePage
= GetConsoleOutputCP();
520 SetConsoleTitle (szWindowTitle
);
530 * look through the internal commands and determine whether or not this
531 * command is one of them. If it is, call the command. If not, call
532 * execute to run it as an external program.
534 * line - the command line of the program to run
539 DoCommand (LPTSTR line
)
541 TCHAR
*com
= NULL
; /* the first word in the command */
544 LPTSTR rest
; /* pointer to the rest of the command line */
549 DebugPrintf (_T("DoCommand: (\'%s\')\n"), line
);
552 com
= malloc( (_tcslen(line
) +512)*sizeof(TCHAR
) );
555 error_out_of_memory();
560 /* Skip over initial white space */
561 while (_istspace (*line
))
567 /* Anything to do ? */
570 if (*rest
== _T('"'))
572 /* treat quoted words specially */
576 while(*rest
!= _T('\0') && *rest
!= _T('"'))
577 *cp
++ = _totlower (*rest
++);
578 if (*rest
== _T('"'))
583 while (!IsDelimiter (*rest
))
584 *cp
++ = _totlower (*rest
++);
588 /* Terminate first word */
591 /* Do not limit commands to MAX_PATH */
593 if(_tcslen(com) > MAX_PATH)
601 /* Skip over whitespace to rest of line */
602 while (_istspace (*rest
))
605 /* Scan internal command table */
606 for (cmdptr
= cmds
;; cmdptr
++)
608 /* If end of table execute ext cmd */
609 if (cmdptr
->name
== NULL
)
611 Execute (line
, com
, rest
);
615 if (!_tcscmp (com
, cmdptr
->name
))
617 cmdptr
->func (com
, rest
);
621 /* The following code handles the case of commands like CD which
622 * are recognised even when the command name and parameter are
623 * not space separated.
629 /* Get length of command name */
630 cl
= _tcslen (cmdptr
->name
);
632 if ((cmdptr
->flags
& CMD_SPECIAL
) &&
633 (!_tcsncmp (cmdptr
->name
, com
, cl
)) &&
634 (_tcschr (_T("\\.-"), *(com
+ cl
))))
636 /* OK its one of the specials...*/
638 /* Terminate first word properly */
641 /* Call with new rest */
642 cmdptr
->func (com
, cstart
+ cl
);
652 * process the command line and execute the appropriate functions
653 * full input/output redirection and piping are supported
656 VOID
ParseCommandLine (LPTSTR cmd
)
658 TCHAR szMsg
[RC_STRING_MAX_SIZE
];
659 TCHAR cmdline
[CMDLINE_LENGTH
];
661 #ifdef FEATURE_REDIRECTION
662 TCHAR in
[CMDLINE_LENGTH
] = _T("");
663 TCHAR out
[CMDLINE_LENGTH
] = _T("");
664 TCHAR err
[CMDLINE_LENGTH
] = _T("");
665 TCHAR szTempPath
[MAX_PATH
] = _T(".\\");
666 TCHAR szFileName
[2][MAX_PATH
] = {_T(""), _T("")};
667 HANDLE hFile
[2] = {INVALID_HANDLE_VALUE
, INVALID_HANDLE_VALUE
};
673 BOOL bNewBatch
= TRUE
;
677 #endif /* FEATURE_REDIRECTION */
679 _tcscpy (cmdline
, cmd
);
683 DebugPrintf (_T("ParseCommandLine: (\'%s\')\n"), s
);
686 #ifdef FEATURE_ALIASES
687 /* expand all aliases */
688 ExpandAlias (s
, CMDLINE_LENGTH
);
689 #endif /* FEATURE_ALIAS */
691 #ifdef FEATURE_REDIRECTION
692 /* find the temp path to store temporary files */
693 Length
= GetTempPath (MAX_PATH
, szTempPath
);
694 if (Length
> 0 && Length
< MAX_PATH
)
696 Attributes
= GetFileAttributes(szTempPath
);
697 if (Attributes
== 0xffffffff ||
698 !(Attributes
& FILE_ATTRIBUTE_DIRECTORY
))
703 if (Length
== 0 || Length
>= MAX_PATH
)
705 _tcscpy(szTempPath
, _T(".\\"));
707 if (szTempPath
[_tcslen (szTempPath
) - 1] != _T('\\'))
708 _tcscat (szTempPath
, _T("\\"));
710 /* get the redirections from the command line */
711 num
= GetRedirection (s
, in
, out
, err
, &nRedirFlags
);
713 /* more efficient, but do we really need to do this? */
714 for (t
= in
; _istspace (*t
); t
++)
718 for (t
= out
; _istspace (*t
); t
++)
722 for (t
= err
; _istspace (*t
); t
++)
726 if(bc
&& !_tcslen (in
) && _tcslen (bc
->In
))
728 if(bc
&& !out
[0] && _tcslen(bc
->Out
))
730 nRedirFlags
|= OUTPUT_APPEND
;
731 _tcscpy(out
, bc
->Out
);
733 if(bc
&& !_tcslen (err
) && _tcslen (bc
->Err
))
735 nRedirFlags
|= ERROR_APPEND
;
736 _tcscpy(err
, bc
->Err
);
740 /* Set up the initial conditions ... */
741 /* preserve STDIN, STDOUT and STDERR handles */
742 hOldConIn
= GetStdHandle (STD_INPUT_HANDLE
);
743 hOldConOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
744 hOldConErr
= GetStdHandle (STD_ERROR_HANDLE
);
750 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
752 /* we need make sure the LastError msg is zero before calling CreateFile */
755 /* Set up pipe for the standard input handler */
756 hFile
= CreateFile (in
, GENERIC_READ
, FILE_SHARE_READ
, &sa
, OPEN_EXISTING
,
757 FILE_ATTRIBUTE_NORMAL
, NULL
);
758 if (hFile
== INVALID_HANDLE_VALUE
)
760 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR1
, szMsg
, RC_STRING_MAX_SIZE
);
761 ConErrPrintf(szMsg
, in
);
765 if (!SetStdHandle (STD_INPUT_HANDLE
, hFile
))
767 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR1
, szMsg
, RC_STRING_MAX_SIZE
);
768 ConErrPrintf(szMsg
, in
);
772 DebugPrintf (_T("Input redirected from: %s\n"), in
);
776 /* Now do all but the last pipe command */
777 *szFileName
[0] = _T('\0');
778 hFile
[0] = INVALID_HANDLE_VALUE
;
782 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
784 /* Create unique temporary file name */
785 GetTempFileName (szTempPath
, _T("CMD"), 0, szFileName
[1]);
787 /* we need make sure the LastError msg is zero before calling CreateFile */
790 /* Set current stdout to temporary file */
791 hFile
[1] = CreateFile (szFileName
[1], GENERIC_WRITE
, 0, &sa
,
792 TRUNCATE_EXISTING
, FILE_ATTRIBUTE_TEMPORARY
, NULL
);
794 if (hFile
[1] == INVALID_HANDLE_VALUE
)
796 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR2
, szMsg
, RC_STRING_MAX_SIZE
);
801 SetStdHandle (STD_OUTPUT_HANDLE
, hFile
[1]);
805 /* close stdout file */
806 SetStdHandle (STD_OUTPUT_HANDLE
, hOldConOut
);
807 if ((hFile
[1] != INVALID_HANDLE_VALUE
) && (hFile
[1] != hOldConOut
))
809 CloseHandle (hFile
[1]);
810 hFile
[1] = INVALID_HANDLE_VALUE
;
813 /* close old stdin file */
814 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
815 if ((hFile
[0] != INVALID_HANDLE_VALUE
) && (hFile
[0] != hOldConIn
))
817 /* delete old stdin file, if it is a real file */
818 CloseHandle (hFile
[0]);
819 hFile
[0] = INVALID_HANDLE_VALUE
;
820 DeleteFile (szFileName
[0]);
821 *szFileName
[0] = _T('\0');
824 /* copy stdout file name to stdin file name */
825 _tcscpy (szFileName
[0], szFileName
[1]);
826 *szFileName
[1] = _T('\0');
828 /* we need make sure the LastError msg is zero before calling CreateFile */
831 /* open new stdin file */
832 hFile
[0] = CreateFile (szFileName
[0], GENERIC_READ
, 0, &sa
,
833 OPEN_EXISTING
, FILE_ATTRIBUTE_TEMPORARY
, NULL
);
834 SetStdHandle (STD_INPUT_HANDLE
, hFile
[0]);
836 s
= s
+ _tcslen (s
) + 1;
839 /* Now set up the end conditions... */
840 /* redirect STDOUT */
843 /* Final output to here */
845 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
847 /* we need make sure the LastError msg is zero before calling CreateFile */
850 hFile
= CreateFile (out
, GENERIC_WRITE
, FILE_SHARE_WRITE
| FILE_SHARE_READ
| FILE_SHARE_DELETE
, &sa
,
851 (nRedirFlags
& OUTPUT_APPEND
) ? OPEN_ALWAYS
: CREATE_ALWAYS
,
852 FILE_ATTRIBUTE_NORMAL
| FILE_FLAG_WRITE_THROUGH
, NULL
);
854 if (hFile
== INVALID_HANDLE_VALUE
)
856 INT size
= _tcslen(out
)-1;
858 if (out
[size
] != _T(':'))
860 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR3
, szMsg
, RC_STRING_MAX_SIZE
);
861 ConErrPrintf(szMsg
, out
);
866 hFile
= CreateFile (out
, GENERIC_WRITE
, FILE_SHARE_WRITE
| FILE_SHARE_READ
| FILE_SHARE_DELETE
, &sa
,
867 (nRedirFlags
& OUTPUT_APPEND
) ? OPEN_ALWAYS
: CREATE_ALWAYS
,
868 FILE_ATTRIBUTE_NORMAL
| FILE_FLAG_WRITE_THROUGH
, NULL
);
870 if (hFile
== INVALID_HANDLE_VALUE
)
872 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR3
, szMsg
, RC_STRING_MAX_SIZE
);
873 ConErrPrintf(szMsg
, out
);
879 if (!SetStdHandle (STD_OUTPUT_HANDLE
, hFile
))
881 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR3
, szMsg
, RC_STRING_MAX_SIZE
);
882 ConErrPrintf(szMsg
, out
);
886 if (nRedirFlags
& OUTPUT_APPEND
)
890 if (GetFileType (hFile
) == FILE_TYPE_DISK
)
891 SetFilePointer (hFile
, 0, &lHighPos
, FILE_END
);
894 DebugPrintf (_T("Output redirected to: %s\n"), out
);
897 else if (hOldConOut
!= INVALID_HANDLE_VALUE
)
899 /* Restore original stdout */
900 HANDLE hOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
901 SetStdHandle (STD_OUTPUT_HANDLE
, hOldConOut
);
902 if (hOldConOut
!= hOut
)
904 hOldConOut
= INVALID_HANDLE_VALUE
;
907 /* redirect STDERR */
910 /* Final output to here */
912 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
914 if (!_tcscmp (err
, out
))
917 DebugPrintf (_T("Stdout and stderr will use the same file!!\n"));
919 DuplicateHandle (GetCurrentProcess (),
920 GetStdHandle (STD_OUTPUT_HANDLE
),
921 GetCurrentProcess (),
922 &hFile
, 0, TRUE
, DUPLICATE_SAME_ACCESS
);
926 hFile
= CreateFile (err
,
928 FILE_SHARE_WRITE
| FILE_SHARE_READ
| FILE_SHARE_DELETE
,
930 (nRedirFlags
& ERROR_APPEND
) ? OPEN_ALWAYS
: CREATE_ALWAYS
,
931 FILE_ATTRIBUTE_NORMAL
| FILE_FLAG_WRITE_THROUGH
,
933 if (hFile
== INVALID_HANDLE_VALUE
)
935 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR3
, szMsg
, RC_STRING_MAX_SIZE
);
936 ConErrPrintf(szMsg
, err
);
941 if (!SetStdHandle (STD_ERROR_HANDLE
, hFile
))
943 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR3
, szMsg
, RC_STRING_MAX_SIZE
);
944 ConErrPrintf(szMsg
, err
);
948 if (nRedirFlags
& ERROR_APPEND
)
952 if (GetFileType (hFile
) == FILE_TYPE_DISK
)
953 SetFilePointer (hFile
, 0, &lHighPos
, FILE_END
);
956 DebugPrintf (_T("Error redirected to: %s\n"), err
);
959 else if (hOldConErr
!= INVALID_HANDLE_VALUE
)
961 /* Restore original stderr */
962 HANDLE hErr
= GetStdHandle (STD_ERROR_HANDLE
);
963 SetStdHandle (STD_ERROR_HANDLE
, hOldConErr
);
964 if (hOldConErr
!= hErr
)
966 hOldConErr
= INVALID_HANDLE_VALUE
;
973 /* process final command */
976 #ifdef FEATURE_REDIRECTION
978 AddBatchRedirection(in
, out
, err
);
979 /* close old stdin file */
980 #if 0 /* buggy implementation */
981 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
982 if ((hFile
[0] != INVALID_HANDLE_VALUE
) &&
983 (hFile
[0] != hOldConIn
))
985 /* delete old stdin file, if it is a real file */
986 CloseHandle (hFile
[0]);
987 hFile
[0] = INVALID_HANDLE_VALUE
;
988 DeleteFile (szFileName
[0]);
989 *szFileName
[0] = _T('\0');
992 /* Restore original STDIN */
993 if (hOldConIn
!= INVALID_HANDLE_VALUE
)
995 HANDLE hIn
= GetStdHandle (STD_INPUT_HANDLE
);
996 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
997 if (hOldConIn
!= hIn
)
999 hOldConIn
= INVALID_HANDLE_VALUE
;
1004 DebugPrintf (_T("Can't restore STDIN! Is invalid!!\n"), out
);
1007 #endif /* buggy implementation */
1010 if (hOldConIn
!= INVALID_HANDLE_VALUE
)
1012 HANDLE hIn
= GetStdHandle (STD_INPUT_HANDLE
);
1013 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
1014 if (hIn
== INVALID_HANDLE_VALUE
)
1017 DebugPrintf (_T("Previous STDIN is invalid!!\n"));
1022 if (GetFileType (hIn
) == FILE_TYPE_DISK
)
1024 if (hFile
[0] == hIn
)
1026 CloseHandle (hFile
[0]);
1027 hFile
[0] = INVALID_HANDLE_VALUE
;
1028 DeleteFile (szFileName
[0]);
1029 *szFileName
[0] = _T('\0');
1034 DebugPrintf (_T("hFile[0] and hIn dont match!!!\n"));
1042 /* Restore original STDOUT */
1043 if (hOldConOut
!= INVALID_HANDLE_VALUE
)
1045 HANDLE hOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
1046 SetStdHandle (STD_OUTPUT_HANDLE
, hOldConOut
);
1047 if (hOldConOut
!= hOut
)
1049 hOldConOut
= INVALID_HANDLE_VALUE
;
1052 /* Restore original STDERR */
1053 if (hOldConErr
!= INVALID_HANDLE_VALUE
)
1055 HANDLE hErr
= GetStdHandle (STD_ERROR_HANDLE
);
1056 SetStdHandle (STD_ERROR_HANDLE
, hOldConErr
);
1057 if (hOldConErr
!= hErr
)
1059 hOldConErr
= INVALID_HANDLE_VALUE
;
1061 #endif /* FEATURE_REDIRECTION */
1066 * do the prompt/input/process loop
1071 ProcessInput (BOOL bFlag
)
1073 TCHAR commandline
[CMDLINE_LENGTH
];
1074 TCHAR readline
[CMDLINE_LENGTH
];
1084 /* if no batch input then... */
1085 if (!(ip
= ReadBatchLine (&bEchoThisLine
)))
1090 ReadCommand (readline
, CMDLINE_LENGTH
);
1092 bEchoThisLine
= FALSE
;
1095 /* skip leading blanks */
1096 while ( _istspace(*ip
) )
1103 if (bSubstitute
&& *ip
== _T('%'))
1121 if ((tp
= FindArg (*ip
- _T('0'))))
1123 cp
= _stpcpy (cp
, tp
);
1131 cp
+= _stprintf (cp
, _T("%u"), nErrorLevel
);
1136 tp
= _tcschr(ip
, _T('%'));
1138 (tp
<= _tcschr(ip
, _T(' ')) - 1))
1144 /* FIXME: Correct error handling when it can not alloc memmory */
1147 if (_tcsicmp(ip
,_T("cd")) ==0)
1149 TCHAR szPath
[MAX_PATH
];
1150 GetCurrentDirectory (MAX_PATH
, szPath
);
1151 cp
= _stpcpy (cp
, szPath
);
1154 else if (_tcsicmp(ip
,_T("time")) ==0)
1160 _sntprintf(szTime
,40,_T("%02d%c%02d%c%02d%c%02d"), t
.wHour
, cTimeSeparator
,t
.wMinute
, cTimeSeparator
,t
.wSecond
, cDecimalSeparator
, t
.wMilliseconds
);
1161 cp
= _stpcpy (cp
, szTime
);
1165 else if (_tcsicmp(ip
,_T("date")) ==0)
1169 GetDateFormat(LOCALE_USER_DEFAULT
, 0, NULL
, _T("ddd"), szDate
, sizeof (szDate
));
1170 cp
= _stpcpy (cp
, szDate
);
1171 cp
= _stpcpy (cp
, _T(" "));
1172 GetDateFormat(LOCALE_USER_DEFAULT
, DATE_SHORTDATE
, NULL
, NULL
, szDate
, sizeof (szDate
));
1173 cp
= _stpcpy (cp
, szDate
);
1177 else if (_tcsicmp(ip
,_T("random")) ==0)
1180 /* Get random number */
1181 _itot(rand(),szRand
,10);
1182 cp
= _stpcpy (cp
, szRand
);
1186 else if (_tcsicmp(ip
,_T("cmdcmdline")) ==0)
1189 /* Get random number */
1190 pargv
= GetCommandLine();
1191 cp
= _stpcpy (cp
, pargv
);
1194 /* %CMDEXTVERSION% */
1195 else if (_tcsicmp(ip
,_T("cmdextversion")) ==0)
1198 /* Set version number to 2 */
1200 cp
= _stpcpy (cp
, szVER
);
1204 else if (_tcsicmp(ip
,_T("errorlevel")) ==0)
1206 evar
= malloc ( size
* sizeof(TCHAR
));
1210 memset(evar
,0,512 * sizeof(TCHAR
));
1211 _itot(nErrorLevel
,evar
,10);
1212 cp
= _stpcpy (cp
, evar
);
1218 evar
= malloc ( 512 * sizeof(TCHAR
));
1222 size
= GetEnvironmentVariable (ip
, evar
, 512);
1223 if(GetLastError() == ERROR_ENVVAR_NOT_FOUND
)
1225 /* if no env var is found you must
1226 continue with what was input*/
1227 cp
= _stpcpy (cp
, _T("%"));
1228 cp
= _stpcpy (cp
, ip
);
1229 cp
= _stpcpy (cp
, _T("%"));
1235 evar
= realloc(evar
,size
* sizeof(TCHAR
) );
1240 size
= GetEnvironmentVariable (ip
, evar
, size
);
1245 cp
= _stpcpy (cp
, evar
);
1265 if (_istcntrl (*ip
))
1269 /* HACK HACK HACK check whether bSubstitute needs to be toggled */
1272 tmp
+= _tcsspn(tmp
,_T(" \t"));
1273 /* first we find and skip and pre-redirections... */
1274 while ( _tcschr(_T("<>"),*tmp
)
1275 || !_tcsncmp(tmp
,_T("1>"),2)
1276 || !_tcsncmp(tmp
,_T("2>"),2) )
1278 if ( _istdigit(*tmp
) )
1282 tmp
+= _tcsspn(tmp
,_T(" \t"));
1283 if ( *tmp
== _T('\"') )
1285 tmp
= _tcschr(tmp
+1,_T('\"'));
1290 tmp
= _tcspbrk(tmp
,_T(" \t"));
1291 tmp
+= _tcsspn(tmp
,_T(" \t"));
1293 /* we should now be pointing to the actual command
1294 * (if there is one yet)*/
1297 /* if we're currently substituting ( which is default )
1298 * check to see if we've parsed out a set/a. if so, we
1299 * need to disable substitution until we come across a
1303 /* look for set /a */
1304 if ( !_tcsnicmp(tmp
,_T("set"),3) )
1307 tmp
+= _tcsspn(tmp
,_T(" \t"));
1308 if ( !_tcsnicmp(tmp
,_T("/a"),2) )
1309 bSubstitute
= FALSE
;
1312 /* if we're not currently substituting, it means we're
1313 * already inside a set /a. now we need to look for
1314 * a redirection in order to turn redirection back on */
1317 /* look for redirector of some kind after the command */
1318 while ( (tmp
= _tcspbrk ( tmp
, _T("^<>|") )) )
1320 if ( *tmp
== _T('^') )
1322 if ( _tcschr(_T("<>|&"), *++tmp
) )
1337 /* strip trailing spaces */
1338 while ((--cp
>= commandline
) && _istspace (*cp
));
1340 *(cp
+ 1) = _T('\0');
1343 /* Echo batch file line */
1347 ConOutPuts (commandline
);
1352 ParseCommandLine (commandline
);
1353 if (bEcho
&& !bIgnoreEcho
)
1355 bIgnoreEcho
= FALSE
;
1358 while (!bCanExit
|| !bExit
);
1365 * control-break handler.
1367 BOOL WINAPI
BreakHandler (DWORD dwCtrlType
)
1370 if ((dwCtrlType
!= CTRL_C_EVENT
) &&
1371 (dwCtrlType
!= CTRL_BREAK_EVENT
))
1374 if (bChildProcessRunning
== TRUE
)
1376 GenerateConsoleCtrlEvent (CTRL_C_EVENT
,
1381 /* FIXME: Handle batch files */
1383 /* FIXME: Print "^C" */
1390 VOID
AddBreakHandler (VOID
)
1392 SetConsoleCtrlHandler ((PHANDLER_ROUTINE
)BreakHandler
, TRUE
);
1396 VOID
RemoveBreakHandler (VOID
)
1398 SetConsoleCtrlHandler ((PHANDLER_ROUTINE
)BreakHandler
, FALSE
);
1403 * show commands and options that are available.
1410 /* print command list */
1411 ConOutResPuts(STRING_CMD_HELP1
);
1414 /* print feature list */
1415 ConOutResPuts(STRING_CMD_HELP2
);
1417 #ifdef FEATURE_ALIASES
1418 ConOutResPuts(STRING_CMD_HELP3
);
1420 #ifdef FEATURE_HISTORY
1421 ConOutResPuts(STRING_CMD_HELP4
);
1423 #ifdef FEATURE_UNIX_FILENAME_COMPLETION
1424 ConOutResPuts(STRING_CMD_HELP5
);
1426 #ifdef FEATURE_DIRECTORY_STACK
1427 ConOutResPuts(STRING_CMD_HELP6
);
1429 #ifdef FEATURE_REDIRECTION
1430 ConOutResPuts(STRING_CMD_HELP7
);
1432 ConOutChar(_T('\n'));
1437 * set up global initializations and process parameters
1439 * argc - number of parameters to command.com
1440 * argv - command-line parameters
1444 Initialize (int argc
, TCHAR
* argv
[])
1446 TCHAR commandline
[CMDLINE_LENGTH
];
1447 TCHAR ModuleName
[_MAX_PATH
+ 1];
1452 //TCHAR *ptr, *cmdLine;
1454 /* get version information */
1455 osvi
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
1456 GetVersionEx (&osvi
);
1458 /* Some people like to run ReactOS cmd.exe on Win98, it helps in the
1459 * build process. So don't link implicitly against ntdll.dll, load it
1460 * dynamically instead */
1462 if (osvi
.dwPlatformId
== VER_PLATFORM_WIN32_NT
)
1464 /* ntdll is always present on NT */
1465 NtDllModule
= GetModuleHandle(TEXT("ntdll.dll"));
1469 /* not all 9x versions have a ntdll.dll, try to load it */
1470 NtDllModule
= LoadLibrary(TEXT("ntdll.dll"));
1473 if (NtDllModule
!= NULL
)
1475 NtQueryInformationProcessPtr
= (NtQueryInformationProcessProc
)GetProcAddress(NtDllModule
, "NtQueryInformationProcess");
1476 NtReadVirtualMemoryPtr
= (NtReadVirtualMemoryProc
)GetProcAddress(NtDllModule
, "NtReadVirtualMemory");
1481 DebugPrintf (_T("[command args:\n"));
1482 for (i
= 0; i
< argc
; i
++)
1484 DebugPrintf (_T("%d. %s\n"), i
, argv
[i
]);
1486 DebugPrintf (_T("]\n"));
1491 /* get default input and output console handles */
1492 hOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
1493 hIn
= GetStdHandle (STD_INPUT_HANDLE
);
1495 /* Set EnvironmentVariable PROMPT if it does not exists any env value.
1496 for you can change the EnvirommentVariable for prompt before cmd start
1497 this patch are not 100% right, if it does not exists a PROMPT value cmd should use
1498 $P$G as defualt not set EnvirommentVariable PROMPT to $P$G if it does not exists */
1499 if (GetEnvironmentVariable(_T("PROMPT"),lpBuffer
, 2 * sizeof(TCHAR
)) == 0)
1500 SetEnvironmentVariable (_T("PROMPT"), _T("$P$G"));
1503 if (argc
>= 2 && !_tcsncmp (argv
[1], _T("/?"), 2))
1505 ConOutResPaging(TRUE
,STRING_CMD_HELP8
);
1508 SetConsoleMode (hIn
, ENABLE_PROCESSED_INPUT
);
1510 #ifdef INCLUDE_CMD_CHDIR
1514 #ifdef FATURE_ALIASES
1520 for (i
= 1; i
< argc
; i
++)
1522 if (!_tcsicmp (argv
[i
], _T("/p")))
1524 if (!IsExistingFile (_T("\\autoexec.bat")))
1526 #ifdef INCLUDE_CMD_DATE
1527 cmd_date (_T(""), _T(""));
1529 #ifdef INCLUDE_CMD_TIME
1530 cmd_time (_T(""), _T(""));
1535 ParseCommandLine (_T("\\autoexec.bat"));
1539 else if (!_tcsicmp (argv
[i
], _T("/c")))
1541 /* This just runs a program and exits */
1545 _tcscpy (commandline
, argv
[i
]);
1548 _tcscat (commandline
, _T(" "));
1549 _tcscat (commandline
, argv
[i
]);
1552 ParseCommandLine(commandline
);
1553 ExitProcess (ProcessInput (TRUE
));
1560 else if (!_tcsicmp (argv
[i
], _T("/k")))
1562 /* This just runs a program and remains */
1566 _tcscpy (commandline
, argv
[i
]);
1569 _tcscat (commandline
, _T(" "));
1570 _tcscat (commandline
, argv
[i
]);
1573 ParseCommandLine(commandline
);
1576 #ifdef INCLUDE_CMD_COLOR
1577 else if (!_tcsnicmp (argv
[i
], _T("/t:"), 3))
1579 /* process /t (color) argument */
1580 wDefColor
= (WORD
)_tcstoul (&argv
[i
][3], NULL
, 16);
1582 SetScreenColor (wColor
, TRUE
);
1588 /* run cmdstart.bat */
1589 if (IsExistingFile (_T("cmdstart.bat")))
1591 ParseCommandLine (_T("cmdstart.bat"));
1593 else if (IsExistingFile (_T("\\cmdstart.bat")))
1595 ParseCommandLine (_T("\\cmdstart.bat"));
1600 /* try to run cmdstart.bat from install dir */
1603 _tcscpy (commandline
, argv
[0]);
1604 p
= _tcsrchr (commandline
, _T('\\')) + 1;
1605 _tcscpy (p
, _T("cmdstart.bat"));
1607 if (IsExistingFile (_T("commandline")))
1609 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR4
, szMsg
, RC_STRING_MAX_SIZE
);
1610 ConErrPrintf(szMsg
, commandline
);
1611 ParseCommandLine (commandline
);
1616 #ifdef FEATURE_DIR_STACK
1617 /* initialize directory stack */
1618 InitDirectoryStack ();
1622 #ifdef FEATURE_HISTORY
1623 /*initialize history*/
1627 /* Set COMSPEC environment variable */
1628 if (0 != GetModuleFileName (NULL
, ModuleName
, _MAX_PATH
+ 1))
1630 ModuleName
[_MAX_PATH
] = _T('\0');
1631 SetEnvironmentVariable (_T("COMSPEC"), ModuleName
);
1634 /* add ctrl break handler */
1639 static VOID
Cleanup (int argc
, TCHAR
*argv
[])
1642 TCHAR szMsg
[RC_STRING_MAX_SIZE
];
1645 /* run cmdexit.bat */
1646 if (IsExistingFile (_T("cmdexit.bat")))
1648 ConErrResPuts(STRING_CMD_ERROR5
);
1650 ParseCommandLine (_T("cmdexit.bat"));
1652 else if (IsExistingFile (_T("\\cmdexit.bat")))
1654 ConErrResPuts (STRING_CMD_ERROR5
);
1655 ParseCommandLine (_T("\\cmdexit.bat"));
1660 /* try to run cmdexit.bat from install dir */
1661 TCHAR commandline
[CMDLINE_LENGTH
];
1664 _tcscpy (commandline
, argv
[0]);
1665 p
= _tcsrchr (commandline
, _T('\\')) + 1;
1666 _tcscpy (p
, _T("cmdexit.bat"));
1668 if (IsExistingFile (_T("commandline")))
1670 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR4
, szMsg
, RC_STRING_MAX_SIZE
);
1671 ConErrPrintf(szMsg
, commandline
);
1672 ParseCommandLine (commandline
);
1677 #ifdef FEATURE_ALIASES
1681 #ifdef FEATURE_DIECTORY_STACK
1682 /* destroy directory stack */
1683 DestroyDirectoryStack ();
1686 #ifdef INCLUDE_CMD_CHDIR
1690 #ifdef FEATURE_HISTORY
1695 /* remove ctrl break handler */
1696 RemoveBreakHandler ();
1697 SetConsoleMode( GetStdHandle( STD_INPUT_HANDLE
),
1698 ENABLE_LINE_INPUT
| ENABLE_PROCESSED_INPUT
| ENABLE_ECHO_INPUT
);
1700 if (NtDllModule
!= NULL
)
1702 FreeLibrary(NtDllModule
);
1708 PWCHAR
* _CommandLineToArgvW(PWCHAR lpCmdLine
, int *pNumArgs
)
1710 PWCHAR
* argvw
= NULL
;
1711 PWCHAR ptr
= lpCmdLine
;
1718 while(lpCmdLine
&& *lpCmdLine
)
1720 while (iswspace(*lpCmdLine
)) lpCmdLine
++;
1723 if ((NumArgs
% 10)==0)
1725 PWCHAR
* old_argvw
= argvw
;
1726 argvw
= malloc((NumArgs
+ 10) * sizeof(PWCHAR
));
1727 memcpy(argvw
, old_argvw
, NumArgs
* sizeof(PWCHAR
));
1730 ptr
= wcschr(lpCmdLine
, L
' ');
1733 len
= ptr
- lpCmdLine
;
1737 len
= wcslen(lpCmdLine
);
1739 str
= malloc((len
+ 1) * sizeof(WCHAR
));
1740 memcpy(str
, lpCmdLine
, len
* sizeof(WCHAR
));
1747 *pNumArgs
= NumArgs
;
1759 int _main (int argc
, char *argv
[])
1762 TCHAR startPath
[MAX_PATH
];
1763 CONSOLE_SCREEN_BUFFER_INFO Info
;
1769 argv
= _CommandLineToArgvW(GetCommandLineW(), &argc
);
1771 argv
= CommandLineToArgvW(GetCommandLineW(), &argc
);
1775 GetCurrentDirectory(MAX_PATH
,startPath
);
1782 hConsole
= CreateFile(_T("CONOUT$"), GENERIC_READ
|GENERIC_WRITE
,
1783 FILE_SHARE_READ
|FILE_SHARE_WRITE
, NULL
,
1784 OPEN_EXISTING
, 0, NULL
);
1785 if (GetConsoleScreenBufferInfo(hConsole
, &Info
) == FALSE
)
1787 ConErrFormatMessage(GetLastError());
1790 wColor
= Info
.wAttributes
;
1793 InputCodePage
= GetConsoleCP();
1794 OutputCodePage
= GetConsoleOutputCP();
1795 CMD_ModuleHandle
= GetModuleHandle(NULL
);
1797 /* check switches on command-line */
1798 Initialize(argc
, argv
);
1800 /* call prompt routine */
1801 nExitCode
= ProcessInput(FALSE
);
1803 /* do the cleanup */
1804 Cleanup(argc
, argv
);