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
146 #include "resource.h"
149 #define NT_SUCCESS(StatCode) ((NTSTATUS)(StatCode) >= 0)
152 typedef NTSTATUS (WINAPI
*NtQueryInformationProcessProc
)(HANDLE
, PROCESSINFOCLASS
,
153 PVOID
, ULONG
, PULONG
);
154 typedef NTSTATUS (WINAPI
*NtReadVirtualMemoryProc
)(HANDLE
, PVOID
, PVOID
, ULONG
, PULONG
);
156 BOOL bExit
= FALSE
; /* indicates EXIT was typed */
157 BOOL bCanExit
= TRUE
; /* indicates if this shell is exitable */
158 BOOL bCtrlBreak
= FALSE
; /* Ctrl-Break or Ctrl-C hit */
159 BOOL bIgnoreEcho
= FALSE
; /* Ignore 'newline' before 'cls' */
160 INT nErrorLevel
= 0; /* Errorlevel of last launched external program */
161 BOOL bChildProcessRunning
= FALSE
;
162 DWORD dwChildProcessId
= 0;
167 HANDLE CMD_ModuleHandle
;
170 static NtQueryInformationProcessProc NtQueryInformationProcessPtr
= NULL
;
171 static NtReadVirtualMemoryProc NtReadVirtualMemoryPtr
= NULL
;
173 #ifdef INCLUDE_CMD_COLOR
174 WORD wColor
; /* current color */
175 WORD wDefColor
; /* default color */
181 * insert commas into a number
184 ConvertULargeInteger (ULARGE_INTEGER num
, LPTSTR des
, INT len
, BOOL bPutSeperator
)
190 if (num
.QuadPart
== 0)
199 while (num
.QuadPart
> 0)
201 if ((((c
+ 1) % (nNumberGroups
+ 1)) == 0) && (bPutSeperator
))
202 temp
[30 - c
++] = cThousandSeparator
;
203 temp
[30 - c
++] = (TCHAR
)(num
.QuadPart
% 10) + _T('0');
207 for (n
= 0; n
<= c
; n
++)
208 des
[n
] = temp
[31 - c
+ n
];
215 * is character a delimeter when used on first word?
218 static BOOL
IsDelimiter (TCHAR c
)
220 return (c
== _T('/') || c
== _T('=') || c
== _T('\0') || _istspace (c
));
224 * Is a process a console process?
226 static BOOL
IsConsoleProcess(HANDLE Process
)
229 PROCESS_BASIC_INFORMATION Info
;
233 if (NULL
== NtQueryInformationProcessPtr
|| NULL
== NtReadVirtualMemoryPtr
)
238 Status
= NtQueryInformationProcessPtr (
239 Process
, ProcessBasicInformation
,
240 &Info
, sizeof(PROCESS_BASIC_INFORMATION
), NULL
);
241 if (! NT_SUCCESS(Status
))
244 DebugPrintf (_T("NtQueryInformationProcess failed with status %08x\n"), Status
);
248 Status
= NtReadVirtualMemoryPtr (
249 Process
, Info
.PebBaseAddress
, &ProcessPeb
,
250 sizeof(PEB
), &BytesRead
);
251 if (! NT_SUCCESS(Status
) || sizeof(PEB
) != BytesRead
)
254 DebugPrintf (_T("Couldn't read virt mem status %08x bytes read %lu\n"), Status
, BytesRead
);
259 return IMAGE_SUBSYSTEM_WINDOWS_CUI
== ProcessPeb
.ImageSubSystem
;
265 #define SHELLEXECUTETEXT "ShellExecuteW"
267 #define SHELLEXECUTETEXT "ShellExecuteA"
270 typedef HINSTANCE (WINAPI
*MYEX
)(
274 LPCTSTR lpParameters
,
281 static BOOL
RunFile(LPTSTR filename
)
288 DebugPrintf (_T("RunFile(%s)\n"), filename
);
290 hShell32
= LoadLibrary(_T("SHELL32.DLL"));
294 DebugPrintf (_T("RunFile: couldn't load SHELL32.DLL!\n"));
299 hShExt
= (MYEX
)(FARPROC
)GetProcAddress(hShell32
, SHELLEXECUTETEXT
);
303 DebugPrintf (_T("RunFile: couldn't find ShellExecuteA/W in SHELL32.DLL!\n"));
305 FreeLibrary(hShell32
);
310 DebugPrintf (_T("RunFile: ShellExecuteA/W is at %x\n"), hShExt
);
313 ret
= (hShExt
)(NULL
, _T("open"), filename
, NULL
, NULL
, SW_SHOWNORMAL
);
316 DebugPrintf (_T("RunFile: ShellExecuteA/W returned %d\n"), (DWORD
)ret
);
319 FreeLibrary(hShell32
);
320 return (((DWORD
)ret
) > 32);
326 * This command (in first) was not found in the command table
328 * Full - whole command line
329 * First - first word on command line
330 * Rest - rest of command line
334 Execute (LPTSTR Full
, LPTSTR First
, LPTSTR Rest
)
336 TCHAR
*szFullName
=NULL
;
341 TCHAR szWindowTitle
[MAX_PATH
];
342 DWORD dwExitCode
= 0;
345 DebugPrintf (_T("Execute: \'%s\' \'%s\'\n"), first
, rest
);
348 /* we need biger buffer that First, Rest, Full are already
349 need rewrite some code to use realloc when it need instead
350 of add 512bytes extra */
352 first
= malloc ( (_tcslen(First
) + 512) * sizeof(TCHAR
));
355 error_out_of_memory();
359 rest
= malloc ( (_tcslen(Rest
) + 512) * sizeof(TCHAR
));
363 error_out_of_memory();
367 full
= malloc ( (_tcslen(Full
) + 512) * sizeof(TCHAR
));
372 error_out_of_memory();
376 szFullName
= malloc ( (_tcslen(Full
) + 512) * sizeof(TCHAR
));
382 error_out_of_memory();
387 /* Though it was already parsed once, we have a different set of rules
388 for parsing before we pass to CreateProccess */
389 if(!_tcschr(Full
,_T('\"')))
391 _tcscpy(first
,First
);
398 BOOL bInside
= FALSE
;
403 /* find the end of the command and start of the args */
404 for(i
= 0; i
< _tcslen(first
); i
++)
406 if(!_tcsncmp(&first
[i
], _T("\""), 1))
408 if(!_tcsncmp(&first
[i
], _T(" "), 1) && !bInside
)
410 _tcscpy(rest
,&first
[i
]);
417 /* remove any slashes */
418 while(i
< _tcslen(first
))
420 if(first
[i
] == _T('\"'))
421 memmove(&first
[i
],&first
[i
+ 1], _tcslen(&first
[i
]) * sizeof(TCHAR
));
425 /* Drop quotes around it just in case there is a space */
426 _tcscpy(full
,_T("\""));
428 _tcscat(full
,_T("\" "));
432 /* check for a drive change */
433 if ((_istalpha (first
[0])) && (!_tcscmp (first
+ 1, _T(":"))))
436 if (!SetCurrentDirectory(first
))
437 /* Guess they changed disc or something, handle that gracefully and get to root */
444 working
= SetCurrentDirectory(str
);
447 if (!working
) ConErrResPuts (STRING_FREE_ERROR1
);
457 /* get the PATH environment variable and parse it */
458 /* search the PATH environment variable for the binary */
459 if (!SearchForExecutable (first
, szFullName
))
461 error_bad_command ();
470 GetConsoleTitle (szWindowTitle
, MAX_PATH
);
472 /* check if this is a .BAT or .CMD file */
473 dot
= _tcsrchr (szFullName
, _T('.'));
474 if (dot
&& (!_tcsicmp (dot
, _T(".bat")) || !_tcsicmp (dot
, _T(".cmd"))))
477 DebugPrintf (_T("[BATCH: %s %s]\n"), szFullName
, rest
);
479 Batch (szFullName
, first
, rest
);
483 /* exec the program */
484 PROCESS_INFORMATION prci
;
488 DebugPrintf (_T("[EXEC: %s %s]\n"), full
, rest
);
490 /* build command line for CreateProcess() */
492 /* fill startup info */
493 memset (&stui
, 0, sizeof (STARTUPINFO
));
494 stui
.cb
= sizeof (STARTUPINFO
);
495 stui
.dwFlags
= STARTF_USESHOWWINDOW
;
496 stui
.wShowWindow
= SW_SHOWDEFAULT
;
498 // return console to standard mode
499 SetConsoleMode (GetStdHandle(STD_INPUT_HANDLE
),
500 ENABLE_LINE_INPUT
| ENABLE_PROCESSED_INPUT
| ENABLE_ECHO_INPUT
);
502 if (CreateProcess (szFullName
,
507 0, /* CREATE_NEW_PROCESS_GROUP */
514 if (IsConsoleProcess(prci
.hProcess
))
516 /* FIXME: Protect this with critical section */
517 bChildProcessRunning
= TRUE
;
518 dwChildProcessId
= prci
.dwProcessId
;
520 WaitForSingleObject (prci
.hProcess
, INFINITE
);
522 /* FIXME: Protect this with critical section */
523 bChildProcessRunning
= FALSE
;
525 GetExitCodeProcess (prci
.hProcess
, &dwExitCode
);
526 nErrorLevel
= (INT
)dwExitCode
;
528 CloseHandle (prci
.hThread
);
529 CloseHandle (prci
.hProcess
);
534 DebugPrintf (_T("[ShellExecute: %s]\n"), full
);
536 // See if we can run this with ShellExecute() ie myfile.xls
540 DebugPrintf (_T("[ShellExecute failed!: %s]\n"), full
);
542 error_bad_command ();
545 // restore console mode
547 GetStdHandle( STD_INPUT_HANDLE
),
548 ENABLE_PROCESSED_INPUT
);
551 /* Get code page if it has been change */
552 InputCodePage
= GetConsoleCP();
553 OutputCodePage
= GetConsoleOutputCP();
554 SetConsoleTitle (szWindowTitle
);
564 * look through the internal commands and determine whether or not this
565 * command is one of them. If it is, call the command. If not, call
566 * execute to run it as an external program.
568 * line - the command line of the program to run
573 DoCommand (LPTSTR line
)
575 TCHAR
*com
= NULL
; /* the first word in the command */
578 LPTSTR rest
; /* pointer to the rest of the command line */
583 DebugPrintf (_T("DoCommand: (\'%s\')\n"), line
);
586 com
= malloc( (_tcslen(line
) +512)*sizeof(TCHAR
) );
589 error_out_of_memory();
594 /* Skip over initial white space */
595 while (_istspace (*line
))
601 /* Anything to do ? */
604 if (*rest
== _T('"'))
606 /* treat quoted words specially */
610 while(*rest
!= _T('\0') && *rest
!= _T('"'))
611 *cp
++ = _totlower (*rest
++);
612 if (*rest
== _T('"'))
617 while (!IsDelimiter (*rest
))
618 *cp
++ = _totlower (*rest
++);
622 /* Terminate first word */
625 /* Do not limit commands to MAX_PATH */
627 if(_tcslen(com) > MAX_PATH)
635 /* Skip over whitespace to rest of line, exclude 'echo' command */
636 if (_tcsicmp (com
, _T("echo")))
638 while (_istspace (*rest
))
642 /* Scan internal command table */
643 for (cmdptr
= cmds
;; cmdptr
++)
645 /* If end of table execute ext cmd */
646 if (cmdptr
->name
== NULL
)
648 Execute (line
, com
, rest
);
652 if (!_tcscmp (com
, cmdptr
->name
))
654 cmdptr
->func (com
, rest
);
658 /* The following code handles the case of commands like CD which
659 * are recognised even when the command name and parameter are
660 * not space separated.
666 /* Get length of command name */
667 cl
= _tcslen (cmdptr
->name
);
669 if ((cmdptr
->flags
& CMD_SPECIAL
) &&
670 (!_tcsncmp (cmdptr
->name
, com
, cl
)) &&
671 (_tcschr (_T("\\.-"), *(com
+ cl
))))
673 /* OK its one of the specials...*/
675 /* Terminate first word properly */
678 /* Call with new rest */
679 cmdptr
->func (com
, cstart
+ cl
);
684 /* Just in case a CTRL+C slipped through a command */
691 * process the command line and execute the appropriate functions
692 * full input/output redirection and piping are supported
695 VOID
ParseCommandLine (LPTSTR cmd
)
697 TCHAR szMsg
[RC_STRING_MAX_SIZE
];
698 TCHAR cmdline
[CMDLINE_LENGTH
];
700 #ifdef FEATURE_REDIRECTION
701 TCHAR in
[CMDLINE_LENGTH
] = _T("");
702 TCHAR out
[CMDLINE_LENGTH
] = _T("");
703 TCHAR err
[CMDLINE_LENGTH
] = _T("");
704 TCHAR szTempPath
[MAX_PATH
] = _T(".\\");
705 TCHAR szFileName
[2][MAX_PATH
] = {_T(""), _T("")};
706 HANDLE hFile
[2] = {INVALID_HANDLE_VALUE
, INVALID_HANDLE_VALUE
};
712 BOOL bNewBatch
= TRUE
;
716 #endif /* FEATURE_REDIRECTION */
718 _tcscpy (cmdline
, cmd
);
722 DebugPrintf (_T("ParseCommandLine: (\'%s\')\n"), s
);
725 #ifdef FEATURE_ALIASES
726 /* expand all aliases */
727 ExpandAlias (s
, CMDLINE_LENGTH
);
728 #endif /* FEATURE_ALIAS */
730 #ifdef FEATURE_REDIRECTION
731 /* find the temp path to store temporary files */
732 Length
= GetTempPath (MAX_PATH
, szTempPath
);
733 if (Length
> 0 && Length
< MAX_PATH
)
735 Attributes
= GetFileAttributes(szTempPath
);
736 if (Attributes
== 0xffffffff ||
737 !(Attributes
& FILE_ATTRIBUTE_DIRECTORY
))
742 if (Length
== 0 || Length
>= MAX_PATH
)
744 _tcscpy(szTempPath
, _T(".\\"));
746 if (szTempPath
[_tcslen (szTempPath
) - 1] != _T('\\'))
747 _tcscat (szTempPath
, _T("\\"));
749 /* get the redirections from the command line */
750 num
= GetRedirection (s
, in
, out
, err
, &nRedirFlags
);
752 /* more efficient, but do we really need to do this? */
753 for (t
= in
; _istspace (*t
); t
++)
757 for (t
= out
; _istspace (*t
); t
++)
761 for (t
= err
; _istspace (*t
); t
++)
765 if(bc
&& !_tcslen (in
) && _tcslen (bc
->In
))
767 if(bc
&& !out
[0] && _tcslen(bc
->Out
))
769 nRedirFlags
|= OUTPUT_APPEND
;
770 _tcscpy(out
, bc
->Out
);
772 if(bc
&& !_tcslen (err
) && _tcslen (bc
->Err
))
774 nRedirFlags
|= ERROR_APPEND
;
775 _tcscpy(err
, bc
->Err
);
779 /* Set up the initial conditions ... */
780 /* preserve STDIN, STDOUT and STDERR handles */
781 hOldConIn
= GetStdHandle (STD_INPUT_HANDLE
);
782 hOldConOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
783 hOldConErr
= GetStdHandle (STD_ERROR_HANDLE
);
789 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
791 /* we need make sure the LastError msg is zero before calling CreateFile */
794 /* Set up pipe for the standard input handler */
795 hFile
= CreateFile (in
, GENERIC_READ
, FILE_SHARE_READ
, &sa
, OPEN_EXISTING
,
796 FILE_ATTRIBUTE_NORMAL
, NULL
);
797 if (hFile
== INVALID_HANDLE_VALUE
)
799 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR1
, szMsg
, RC_STRING_MAX_SIZE
);
800 ConErrPrintf(szMsg
, in
);
804 if (!SetStdHandle (STD_INPUT_HANDLE
, hFile
))
806 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR1
, szMsg
, RC_STRING_MAX_SIZE
);
807 ConErrPrintf(szMsg
, in
);
811 DebugPrintf (_T("Input redirected from: %s\n"), in
);
815 /* Now do all but the last pipe command */
816 *szFileName
[0] = _T('\0');
817 hFile
[0] = INVALID_HANDLE_VALUE
;
821 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
823 /* Create unique temporary file name */
824 GetTempFileName (szTempPath
, _T("CMD"), 0, szFileName
[1]);
826 /* we need make sure the LastError msg is zero before calling CreateFile */
829 /* Set current stdout to temporary file */
830 hFile
[1] = CreateFile (szFileName
[1], GENERIC_WRITE
, 0, &sa
,
831 TRUNCATE_EXISTING
, FILE_ATTRIBUTE_TEMPORARY
, NULL
);
833 if (hFile
[1] == INVALID_HANDLE_VALUE
)
835 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR2
, szMsg
, RC_STRING_MAX_SIZE
);
840 SetStdHandle (STD_OUTPUT_HANDLE
, hFile
[1]);
844 /* close stdout file */
845 SetStdHandle (STD_OUTPUT_HANDLE
, hOldConOut
);
846 if ((hFile
[1] != INVALID_HANDLE_VALUE
) && (hFile
[1] != hOldConOut
))
848 CloseHandle (hFile
[1]);
849 hFile
[1] = INVALID_HANDLE_VALUE
;
852 /* close old stdin file */
853 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
854 if ((hFile
[0] != INVALID_HANDLE_VALUE
) && (hFile
[0] != hOldConIn
))
856 /* delete old stdin file, if it is a real file */
857 CloseHandle (hFile
[0]);
858 hFile
[0] = INVALID_HANDLE_VALUE
;
859 DeleteFile (szFileName
[0]);
860 *szFileName
[0] = _T('\0');
863 /* copy stdout file name to stdin file name */
864 _tcscpy (szFileName
[0], szFileName
[1]);
865 *szFileName
[1] = _T('\0');
867 /* we need make sure the LastError msg is zero before calling CreateFile */
870 /* open new stdin file */
871 hFile
[0] = CreateFile (szFileName
[0], GENERIC_READ
, 0, &sa
,
872 OPEN_EXISTING
, FILE_ATTRIBUTE_TEMPORARY
, NULL
);
873 SetStdHandle (STD_INPUT_HANDLE
, hFile
[0]);
875 s
= s
+ _tcslen (s
) + 1;
878 /* Now set up the end conditions... */
879 /* redirect STDOUT */
882 /* Final output to here */
884 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
886 /* we need make sure the LastError msg is zero before calling CreateFile */
889 hFile
= CreateFile (out
, GENERIC_WRITE
, FILE_SHARE_WRITE
| FILE_SHARE_READ
| FILE_SHARE_DELETE
, &sa
,
890 (nRedirFlags
& OUTPUT_APPEND
) ? OPEN_ALWAYS
: CREATE_ALWAYS
,
891 FILE_ATTRIBUTE_NORMAL
| FILE_FLAG_WRITE_THROUGH
, NULL
);
893 if (hFile
== INVALID_HANDLE_VALUE
)
895 INT size
= _tcslen(out
)-1;
897 if (out
[size
] != _T(':'))
899 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR3
, szMsg
, RC_STRING_MAX_SIZE
);
900 ConErrPrintf(szMsg
, out
);
905 hFile
= CreateFile (out
, GENERIC_WRITE
, FILE_SHARE_WRITE
| FILE_SHARE_READ
| FILE_SHARE_DELETE
, &sa
,
906 (nRedirFlags
& OUTPUT_APPEND
) ? OPEN_ALWAYS
: CREATE_ALWAYS
,
907 FILE_ATTRIBUTE_NORMAL
| FILE_FLAG_WRITE_THROUGH
, NULL
);
909 if (hFile
== INVALID_HANDLE_VALUE
)
911 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR3
, szMsg
, RC_STRING_MAX_SIZE
);
912 ConErrPrintf(szMsg
, out
);
918 if (!SetStdHandle (STD_OUTPUT_HANDLE
, hFile
))
920 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR3
, szMsg
, RC_STRING_MAX_SIZE
);
921 ConErrPrintf(szMsg
, out
);
925 if (nRedirFlags
& OUTPUT_APPEND
)
929 if (GetFileType (hFile
) == FILE_TYPE_DISK
)
930 SetFilePointer (hFile
, 0, &lHighPos
, FILE_END
);
933 DebugPrintf (_T("Output redirected to: %s\n"), out
);
936 else if (hOldConOut
!= INVALID_HANDLE_VALUE
)
938 /* Restore original stdout */
939 HANDLE hOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
940 SetStdHandle (STD_OUTPUT_HANDLE
, hOldConOut
);
941 if (hOldConOut
!= hOut
)
943 hOldConOut
= INVALID_HANDLE_VALUE
;
946 /* redirect STDERR */
949 /* Final output to here */
951 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
953 if (!_tcscmp (err
, out
))
956 DebugPrintf (_T("Stdout and stderr will use the same file!!\n"));
958 DuplicateHandle (GetCurrentProcess (),
959 GetStdHandle (STD_OUTPUT_HANDLE
),
960 GetCurrentProcess (),
961 &hFile
, 0, TRUE
, DUPLICATE_SAME_ACCESS
);
965 hFile
= CreateFile (err
,
967 FILE_SHARE_WRITE
| FILE_SHARE_READ
| FILE_SHARE_DELETE
,
969 (nRedirFlags
& ERROR_APPEND
) ? OPEN_ALWAYS
: CREATE_ALWAYS
,
970 FILE_ATTRIBUTE_NORMAL
| FILE_FLAG_WRITE_THROUGH
,
972 if (hFile
== INVALID_HANDLE_VALUE
)
974 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR3
, szMsg
, RC_STRING_MAX_SIZE
);
975 ConErrPrintf(szMsg
, err
);
980 if (!SetStdHandle (STD_ERROR_HANDLE
, hFile
))
982 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR3
, szMsg
, RC_STRING_MAX_SIZE
);
983 ConErrPrintf(szMsg
, err
);
987 if (nRedirFlags
& ERROR_APPEND
)
991 if (GetFileType (hFile
) == FILE_TYPE_DISK
)
992 SetFilePointer (hFile
, 0, &lHighPos
, FILE_END
);
995 DebugPrintf (_T("Error redirected to: %s\n"), err
);
998 else if (hOldConErr
!= INVALID_HANDLE_VALUE
)
1000 /* Restore original stderr */
1001 HANDLE hErr
= GetStdHandle (STD_ERROR_HANDLE
);
1002 SetStdHandle (STD_ERROR_HANDLE
, hOldConErr
);
1003 if (hOldConErr
!= hErr
)
1005 hOldConErr
= INVALID_HANDLE_VALUE
;
1012 /* process final command */
1015 #ifdef FEATURE_REDIRECTION
1017 AddBatchRedirection(in
, out
, err
);
1018 /* close old stdin file */
1019 #if 0 /* buggy implementation */
1020 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
1021 if ((hFile
[0] != INVALID_HANDLE_VALUE
) &&
1022 (hFile
[0] != hOldConIn
))
1024 /* delete old stdin file, if it is a real file */
1025 CloseHandle (hFile
[0]);
1026 hFile
[0] = INVALID_HANDLE_VALUE
;
1027 DeleteFile (szFileName
[0]);
1028 *szFileName
[0] = _T('\0');
1031 /* Restore original STDIN */
1032 if (hOldConIn
!= INVALID_HANDLE_VALUE
)
1034 HANDLE hIn
= GetStdHandle (STD_INPUT_HANDLE
);
1035 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
1036 if (hOldConIn
!= hIn
)
1038 hOldConIn
= INVALID_HANDLE_VALUE
;
1043 DebugPrintf (_T("Can't restore STDIN! Is invalid!!\n"), out
);
1046 #endif /* buggy implementation */
1049 if (hOldConIn
!= INVALID_HANDLE_VALUE
)
1051 HANDLE hIn
= GetStdHandle (STD_INPUT_HANDLE
);
1052 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
1053 if (hIn
== INVALID_HANDLE_VALUE
)
1056 DebugPrintf (_T("Previous STDIN is invalid!!\n"));
1061 if (GetFileType (hIn
) == FILE_TYPE_DISK
)
1063 if (hFile
[0] == hIn
)
1065 CloseHandle (hFile
[0]);
1066 hFile
[0] = INVALID_HANDLE_VALUE
;
1067 DeleteFile (szFileName
[0]);
1068 *szFileName
[0] = _T('\0');
1073 DebugPrintf (_T("hFile[0] and hIn dont match!!!\n"));
1081 /* Restore original STDOUT */
1082 if (hOldConOut
!= INVALID_HANDLE_VALUE
)
1084 HANDLE hOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
1085 SetStdHandle (STD_OUTPUT_HANDLE
, hOldConOut
);
1086 if (hOldConOut
!= hOut
)
1088 hOldConOut
= INVALID_HANDLE_VALUE
;
1091 /* Restore original STDERR */
1092 if (hOldConErr
!= INVALID_HANDLE_VALUE
)
1094 HANDLE hErr
= GetStdHandle (STD_ERROR_HANDLE
);
1095 SetStdHandle (STD_ERROR_HANDLE
, hOldConErr
);
1096 if (hOldConErr
!= hErr
)
1098 hOldConErr
= INVALID_HANDLE_VALUE
;
1100 #endif /* FEATURE_REDIRECTION */
1104 GrowIfNecessary ( UINT needed
, LPTSTR
* ret
, UINT
* retlen
)
1106 if ( *ret
&& needed
< *retlen
)
1111 *ret
= (LPTSTR
)malloc ( *retlen
* sizeof(TCHAR
) );
1113 SetLastError ( ERROR_OUTOFMEMORY
);
1114 return *ret
!= NULL
;
1118 GetEnvVarOrSpecial ( LPCTSTR varName
)
1120 static LPTSTR ret
= NULL
;
1121 static UINT retlen
= 0;
1124 size
= GetEnvironmentVariable ( varName
, ret
, retlen
);
1125 if ( size
> retlen
)
1127 if ( !GrowIfNecessary ( size
, &ret
, &retlen
) )
1129 size
= GetEnvironmentVariable ( varName
, ret
, retlen
);
1134 /* env var doesn't exist, look for a "special" one */
1136 if (_tcsicmp(varName
,_T("cd")) ==0)
1138 size
= GetCurrentDirectory ( retlen
, ret
);
1139 if ( size
> retlen
)
1141 if ( !GrowIfNecessary ( size
, &ret
, &retlen
) )
1143 size
= GetCurrentDirectory ( retlen
, ret
);
1150 else if (_tcsicmp(varName
,_T("time")) ==0)
1153 if ( !GrowIfNecessary ( MAX_PATH
, &ret
, &retlen
) )
1156 _sntprintf ( ret
, retlen
, _T("%02d%c%02d%c%02d%c%02d"),
1157 t
.wHour
, cTimeSeparator
, t
.wMinute
, cTimeSeparator
,
1158 t
.wSecond
, cDecimalSeparator
, t
.wMilliseconds
);
1162 else if (_tcsicmp(varName
,_T("date")) ==0)
1166 if ( !GrowIfNecessary ( MAX_PATH
, &ret
, &retlen
) )
1168 size
= GetDateFormat(LOCALE_USER_DEFAULT
, 0, NULL
, _T("ddd"), ret
, retlen
);
1169 /* TODO FIXME - test whether GetDateFormat() can return a value indicating the buffer wasn't big enough */
1172 tmp
= ret
+ _tcslen(ret
);
1174 size
= GetDateFormat(LOCALE_USER_DEFAULT
, DATE_SHORTDATE
, NULL
, NULL
, tmp
, retlen
-(tmp
-ret
));
1175 /* TODO FIXME - test whether GetDateFormat() can return a value indicating the buffer wasn't big enough */
1182 else if (_tcsicmp(varName
,_T("random")) ==0)
1184 if ( !GrowIfNecessary ( MAX_PATH
, &ret
, &retlen
) )
1186 /* Get random number */
1187 _itot(rand(),ret
,10);
1192 else if (_tcsicmp(varName
,_T("cmdcmdline")) ==0)
1194 return GetCommandLine();
1197 /* %CMDEXTVERSION% */
1198 else if (_tcsicmp(varName
,_T("cmdextversion")) ==0)
1200 if ( !GrowIfNecessary ( MAX_PATH
, &ret
, &retlen
) )
1202 /* Set version number to 2 */
1208 else if (_tcsicmp(varName
,_T("errorlevel")) ==0)
1210 if ( !GrowIfNecessary ( MAX_PATH
, &ret
, &retlen
) )
1212 _itot(nErrorLevel
,ret
,10);
1216 GrowIfNecessary(_tcslen(varName
) + 2, &ret
, &retlen
);
1217 _stprintf(ret
,_T("%%%s%%"),varName
);
1218 return ret
; /* not found - return orginal string */
1222 GetParsedEnvVar ( LPCTSTR varName
, UINT
* varNameLen
, BOOL ModeSetA
)
1224 static LPTSTR ret
= NULL
;
1225 static UINT retlen
= 0;
1232 if ( *varName
++ != '%' )
1246 if ((tmp
= FindArg (*varName
- _T('0'))))
1252 if ( !GrowIfNecessary ( _tcslen(tmp
)+1, &ret
, &retlen
) )
1254 _tcscpy ( ret
, tmp
);
1257 if ( !GrowIfNecessary ( 3, &ret
, &retlen
) )
1267 if ( !GrowIfNecessary ( 2, &ret
, &retlen
) )
1276 /* TODO FIXME 10 is only max size for 32-bit */
1277 if ( !GrowIfNecessary ( 11, &ret
, &retlen
) )
1279 _sntprintf ( ret
, retlen
, _T("%u"), nErrorLevel
);
1287 /* HACK for set/a */
1288 if ( !GrowIfNecessary ( 2, &ret
, &retlen
) )
1296 p
= _tcschr ( varName
, _T('%') );
1299 SetLastError ( ERROR_INVALID_PARAMETER
);
1304 *varNameLen
= size
+ 2;
1305 p
= alloca ( (size
+1) * sizeof(TCHAR
) );
1306 memmove ( p
, varName
, size
* sizeof(TCHAR
) );
1309 return GetEnvVarOrSpecial ( varName
);
1314 * do the prompt/input/process loop
1319 ProcessInput (BOOL bFlag
)
1321 TCHAR commandline
[CMDLINE_LENGTH
];
1322 TCHAR readline
[CMDLINE_LENGTH
];
1332 /* if no batch input then... */
1333 if (!(ip
= ReadBatchLine (&bEchoThisLine
)))
1338 ReadCommand (readline
, CMDLINE_LENGTH
);
1340 bEchoThisLine
= FALSE
;
1348 /* skip leading blanks */
1349 while ( _istspace(*ip
) )
1356 if ( *ip
== _T('%') )
1359 LPCTSTR envVal
= GetParsedEnvVar ( ip
, &envNameLen
, bModeSetA
);
1363 cp
= _stpcpy ( cp
, envVal
);
1367 if (_istcntrl (*ip
))
1371 /* HACK HACK HACK check whether bModeSetA needs to be toggled */
1374 tmp
+= _tcsspn(tmp
,_T(" \t"));
1375 /* first we find and skip and pre-redirections... */
1376 while ( _tcschr(_T("<>"),*tmp
)
1377 || !_tcsncmp(tmp
,_T("1>"),2)
1378 || !_tcsncmp(tmp
,_T("2>"),2) )
1380 if ( _istdigit(*tmp
) )
1384 tmp
+= _tcsspn(tmp
,_T(" \t"));
1385 if ( *tmp
== _T('\"') )
1387 tmp
= _tcschr(tmp
+1,_T('\"'));
1392 tmp
= _tcspbrk(tmp
,_T(" \t"));
1393 tmp
+= _tcsspn(tmp
,_T(" \t"));
1395 /* we should now be pointing to the actual command
1396 * (if there is one yet)*/
1399 /* if we're currently substituting ( which is default )
1400 * check to see if we've parsed out a set/a. if so, we
1401 * need to disable substitution until we come across a
1405 /* look for set /a */
1406 if ( !_tcsnicmp(tmp
,_T("set"),3) )
1409 tmp
+= _tcsspn(tmp
,_T(" \t"));
1410 if ( !_tcsnicmp(tmp
,_T("/a"),2) )
1414 /* if we're not currently substituting, it means we're
1415 * already inside a set /a. now we need to look for
1416 * a redirection in order to turn redirection back on */
1419 /* look for redirector of some kind after the command */
1420 while ( (tmp
= _tcspbrk ( tmp
, _T("^<>|") )) )
1422 if ( *tmp
== _T('^') )
1424 if ( _tcschr(_T("<>|&"), *++tmp
) && *tmp
)
1439 /* strip trailing spaces */
1440 while ((--cp
>= commandline
) && _istspace (*cp
));
1442 *(cp
+ 1) = _T('\0');
1445 /* Echo batch file line */
1449 ConOutPuts (commandline
);
1454 ParseCommandLine (commandline
);
1455 if (bEcho
&& !bIgnoreEcho
&& (!bIsBatch
|| bEchoThisLine
))
1457 bIgnoreEcho
= FALSE
;
1460 while (!bCanExit
|| !bExit
);
1467 * control-break handler.
1469 BOOL WINAPI
BreakHandler (DWORD dwCtrlType
)
1472 static BOOL SelfGenerated
= FALSE
;
1474 if ((dwCtrlType
!= CTRL_C_EVENT
) &&
1475 (dwCtrlType
!= CTRL_BREAK_EVENT
))
1483 SelfGenerated
= FALSE
;
1488 if (bChildProcessRunning
== TRUE
)
1490 SelfGenerated
= TRUE
;
1491 GenerateConsoleCtrlEvent (dwCtrlType
, 0);
1496 /* FIXME: Handle batch files */
1498 //ConOutPrintf(_T("^C"));
1505 VOID
AddBreakHandler (VOID
)
1507 SetConsoleCtrlHandler ((PHANDLER_ROUTINE
)BreakHandler
, TRUE
);
1511 VOID
RemoveBreakHandler (VOID
)
1513 SetConsoleCtrlHandler ((PHANDLER_ROUTINE
)BreakHandler
, FALSE
);
1518 * show commands and options that are available.
1525 /* print command list */
1526 ConOutResPuts(STRING_CMD_HELP1
);
1529 /* print feature list */
1530 ConOutResPuts(STRING_CMD_HELP2
);
1532 #ifdef FEATURE_ALIASES
1533 ConOutResPuts(STRING_CMD_HELP3
);
1535 #ifdef FEATURE_HISTORY
1536 ConOutResPuts(STRING_CMD_HELP4
);
1538 #ifdef FEATURE_UNIX_FILENAME_COMPLETION
1539 ConOutResPuts(STRING_CMD_HELP5
);
1541 #ifdef FEATURE_DIRECTORY_STACK
1542 ConOutResPuts(STRING_CMD_HELP6
);
1544 #ifdef FEATURE_REDIRECTION
1545 ConOutResPuts(STRING_CMD_HELP7
);
1547 ConOutChar(_T('\n'));
1552 * set up global initializations and process parameters
1554 * argc - number of parameters to command.com
1555 * argv - command-line parameters
1559 Initialize (int argc
, TCHAR
* argv
[])
1561 TCHAR commandline
[CMDLINE_LENGTH
];
1562 TCHAR ModuleName
[_MAX_PATH
+ 1];
1567 //TCHAR *ptr, *cmdLine;
1569 /* get version information */
1570 osvi
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
1571 GetVersionEx (&osvi
);
1573 /* Some people like to run ReactOS cmd.exe on Win98, it helps in the
1574 * build process. So don't link implicitly against ntdll.dll, load it
1575 * dynamically instead */
1577 if (osvi
.dwPlatformId
== VER_PLATFORM_WIN32_NT
)
1579 /* ntdll is always present on NT */
1580 NtDllModule
= GetModuleHandle(TEXT("ntdll.dll"));
1584 /* not all 9x versions have a ntdll.dll, try to load it */
1585 NtDllModule
= LoadLibrary(TEXT("ntdll.dll"));
1588 if (NtDllModule
!= NULL
)
1590 NtQueryInformationProcessPtr
= (NtQueryInformationProcessProc
)GetProcAddress(NtDllModule
, "NtQueryInformationProcess");
1591 NtReadVirtualMemoryPtr
= (NtReadVirtualMemoryProc
)GetProcAddress(NtDllModule
, "NtReadVirtualMemory");
1596 DebugPrintf (_T("[command args:\n"));
1597 for (i
= 0; i
< argc
; i
++)
1599 DebugPrintf (_T("%d. %s\n"), i
, argv
[i
]);
1601 DebugPrintf (_T("]\n"));
1606 /* get default input and output console handles */
1607 hOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
1608 hIn
= GetStdHandle (STD_INPUT_HANDLE
);
1610 /* Set EnvironmentVariable PROMPT if it does not exists any env value.
1611 for you can change the EnvirommentVariable for prompt before cmd start
1612 this patch are not 100% right, if it does not exists a PROMPT value cmd should use
1613 $P$G as defualt not set EnvirommentVariable PROMPT to $P$G if it does not exists */
1614 if (GetEnvironmentVariable(_T("PROMPT"),lpBuffer
, sizeof(lpBuffer
) / sizeof(lpBuffer
[0])) == 0)
1615 SetEnvironmentVariable (_T("PROMPT"), _T("$P$G"));
1618 if (argc
>= 2 && !_tcsncmp (argv
[1], _T("/?"), 2))
1620 ConOutResPaging(TRUE
,STRING_CMD_HELP8
);
1623 SetConsoleMode (hIn
, ENABLE_PROCESSED_INPUT
);
1625 #ifdef INCLUDE_CMD_CHDIR
1629 #ifdef FATURE_ALIASES
1635 for (i
= 1; i
< argc
; i
++)
1637 if (!_tcsicmp (argv
[i
], _T("/p")))
1639 if (!IsExistingFile (_T("\\autoexec.bat")))
1641 #ifdef INCLUDE_CMD_DATE
1642 cmd_date (_T(""), _T(""));
1644 #ifdef INCLUDE_CMD_TIME
1645 cmd_time (_T(""), _T(""));
1650 ParseCommandLine (_T("\\autoexec.bat"));
1654 else if (!_tcsicmp (argv
[i
], _T("/c")))
1656 /* This just runs a program and exits */
1660 _tcscpy (commandline
, argv
[i
]);
1663 _tcscat (commandline
, _T(" "));
1664 _tcscat (commandline
, argv
[i
]);
1667 ParseCommandLine(commandline
);
1668 ExitProcess (ProcessInput (TRUE
));
1675 else if (!_tcsicmp (argv
[i
], _T("/k")))
1677 /* This just runs a program and remains */
1681 _tcscpy (commandline
, _T("\""));
1682 _tcscat (commandline
, argv
[i
]);
1683 _tcscat (commandline
, _T("\""));
1686 _tcscat (commandline
, _T(" "));
1687 _tcscat (commandline
, argv
[i
]);
1689 ParseCommandLine(commandline
);
1692 #ifdef INCLUDE_CMD_COLOR
1693 else if (!_tcsnicmp (argv
[i
], _T("/t:"), 3))
1695 /* process /t (color) argument */
1696 wDefColor
= (WORD
)_tcstoul (&argv
[i
][3], NULL
, 16);
1698 SetScreenColor (wColor
, TRUE
);
1704 /* run cmdstart.bat */
1705 if (IsExistingFile (_T("cmdstart.bat")))
1707 ParseCommandLine (_T("cmdstart.bat"));
1709 else if (IsExistingFile (_T("\\cmdstart.bat")))
1711 ParseCommandLine (_T("\\cmdstart.bat"));
1714 #ifdef FEATURE_DIR_STACK
1715 /* initialize directory stack */
1716 InitDirectoryStack ();
1720 #ifdef FEATURE_HISTORY
1721 /*initialize history*/
1725 /* Set COMSPEC environment variable */
1726 if (0 != GetModuleFileName (NULL
, ModuleName
, _MAX_PATH
+ 1))
1728 ModuleName
[_MAX_PATH
] = _T('\0');
1729 SetEnvironmentVariable (_T("COMSPEC"), ModuleName
);
1732 /* add ctrl break handler */
1737 static VOID
Cleanup (int argc
, TCHAR
*argv
[])
1739 /* run cmdexit.bat */
1740 if (IsExistingFile (_T("cmdexit.bat")))
1742 ConErrResPuts(STRING_CMD_ERROR5
);
1744 ParseCommandLine (_T("cmdexit.bat"));
1746 else if (IsExistingFile (_T("\\cmdexit.bat")))
1748 ConErrResPuts (STRING_CMD_ERROR5
);
1749 ParseCommandLine (_T("\\cmdexit.bat"));
1752 #ifdef FEATURE_ALIASES
1756 #ifdef FEATURE_DIECTORY_STACK
1757 /* destroy directory stack */
1758 DestroyDirectoryStack ();
1761 #ifdef INCLUDE_CMD_CHDIR
1765 #ifdef FEATURE_HISTORY
1770 /* remove ctrl break handler */
1771 RemoveBreakHandler ();
1772 SetConsoleMode( GetStdHandle( STD_INPUT_HANDLE
),
1773 ENABLE_LINE_INPUT
| ENABLE_PROCESSED_INPUT
| ENABLE_ECHO_INPUT
);
1775 if (NtDllModule
!= NULL
)
1777 FreeLibrary(NtDllModule
);
1787 int _main (int argc
, char *argv
[])
1790 TCHAR startPath
[MAX_PATH
];
1791 CONSOLE_SCREEN_BUFFER_INFO Info
;
1796 argv
= CommandLineToArgvW(GetCommandLineW(), &argc
);
1799 GetCurrentDirectory(MAX_PATH
,startPath
);
1806 hConsole
= CreateFile(_T("CONOUT$"), GENERIC_READ
|GENERIC_WRITE
,
1807 FILE_SHARE_READ
|FILE_SHARE_WRITE
, NULL
,
1808 OPEN_EXISTING
, 0, NULL
);
1809 if (GetConsoleScreenBufferInfo(hConsole
, &Info
) == FALSE
)
1811 ConErrFormatMessage(GetLastError());
1814 wColor
= Info
.wAttributes
;
1817 InputCodePage
= GetConsoleCP();
1818 OutputCodePage
= GetConsoleOutputCP();
1819 CMD_ModuleHandle
= GetModuleHandle(NULL
);
1821 /* check switches on command-line */
1822 Initialize(argc
, argv
);
1824 /* call prompt routine */
1825 nExitCode
= ProcessInput(FALSE
);
1827 /* do the cleanup */
1828 Cleanup(argc
, argv
);