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 */
179 * is character a delimeter when used on first word?
183 static BOOL
IsDelimiter (TCHAR c
)
185 return (c
== _T('/') || c
== _T('=') || c
== _T('\0') || _istspace (c
));
189 * Is a process a console process?
191 static BOOL
IsConsoleProcess(HANDLE Process
)
194 PROCESS_BASIC_INFORMATION Info
;
198 if (NULL
== NtQueryInformationProcessPtr
|| NULL
== NtReadVirtualMemoryPtr
)
203 Status
= NtQueryInformationProcessPtr (
204 Process
, ProcessBasicInformation
,
205 &Info
, sizeof(PROCESS_BASIC_INFORMATION
), NULL
);
206 if (! NT_SUCCESS(Status
))
209 DebugPrintf (_T("NtQueryInformationProcess failed with status %08x\n"), Status
);
213 Status
= NtReadVirtualMemoryPtr (
214 Process
, Info
.PebBaseAddress
, &ProcessPeb
,
215 sizeof(PEB
), &BytesRead
);
216 if (! NT_SUCCESS(Status
) || sizeof(PEB
) != BytesRead
)
219 DebugPrintf (_T("Couldn't read virt mem status %08x bytes read %lu\n"), Status
, BytesRead
);
224 return IMAGE_SUBSYSTEM_WINDOWS_CUI
== ProcessPeb
.ImageSubSystem
;
230 #define SHELLEXECUTETEXT "ShellExecuteW"
232 #define SHELLEXECUTETEXT "ShellExecuteA"
235 typedef HINSTANCE (WINAPI
*MYEX
)(
239 LPCTSTR lpParameters
,
246 static BOOL
RunFile(LPTSTR filename
)
253 DebugPrintf (_T("RunFile(%s)\n"), filename
);
255 hShell32
= LoadLibrary(_T("SHELL32.DLL"));
259 DebugPrintf (_T("RunFile: couldn't load SHELL32.DLL!\n"));
264 hShExt
= (MYEX
)(FARPROC
)GetProcAddress(hShell32
, SHELLEXECUTETEXT
);
268 DebugPrintf (_T("RunFile: couldn't find ShellExecuteA/W in SHELL32.DLL!\n"));
270 FreeLibrary(hShell32
);
275 DebugPrintf (_T("RunFile: ShellExecuteA/W is at %x\n"), hShExt
);
278 ret
= (hShExt
)(NULL
, _T("open"), filename
, NULL
, NULL
, SW_SHOWNORMAL
);
281 DebugPrintf (_T("RunFile: ShellExecuteA/W returned %d\n"), (DWORD
)ret
);
284 FreeLibrary(hShell32
);
285 return (((DWORD
)ret
) > 32);
291 * This command (in first) was not found in the command table
293 * Full - whole command line
294 * First - first word on command line
295 * Rest - rest of command line
299 Execute (LPTSTR Full
, LPTSTR First
, LPTSTR Rest
)
301 TCHAR
*szFullName
=NULL
;
306 TCHAR szWindowTitle
[MAX_PATH
];
307 DWORD dwExitCode
= 0;
310 DebugPrintf (_T("Execute: \'%s\' \'%s\'\n"), first
, rest
);
313 /* we need biger buffer that First, Rest, Full are already
314 need rewrite some code to use realloc when it need instead
315 of add 512bytes extra */
317 first
= malloc ( (_tcslen(First
) + 512) * sizeof(TCHAR
));
320 error_out_of_memory();
324 rest
= malloc ( (_tcslen(Rest
) + 512) * sizeof(TCHAR
));
328 error_out_of_memory();
332 full
= malloc ( (_tcslen(Full
) + 512) * sizeof(TCHAR
));
337 error_out_of_memory();
341 szFullName
= malloc ( (_tcslen(Full
) + 512) * sizeof(TCHAR
));
347 error_out_of_memory();
352 /* Though it was already parsed once, we have a different set of rules
353 for parsing before we pass to CreateProccess */
354 if(!_tcschr(Full
,_T('\"')))
356 _tcscpy(first
,First
);
363 BOOL bInside
= FALSE
;
368 /* find the end of the command and start of the args */
369 for(i
= 0; i
< _tcslen(first
); i
++)
371 if(!_tcsncmp(&first
[i
], _T("\""), 1))
373 if(!_tcsncmp(&first
[i
], _T(" "), 1) && !bInside
)
375 _tcscpy(rest
,&first
[i
]);
382 /* remove any slashes */
383 while(i
< _tcslen(first
))
385 if(first
[i
] == _T('\"'))
386 memmove(&first
[i
],&first
[i
+ 1], _tcslen(&first
[i
]) * sizeof(TCHAR
));
390 /* Drop quotes around it just in case there is a space */
391 _tcscpy(full
,_T("\""));
393 _tcscat(full
,_T("\" "));
397 /* check for a drive change */
398 if ((_istalpha (first
[0])) && (!_tcscmp (first
+ 1, _T(":"))))
401 if (!SetCurrentDirectory(first
))
402 /* Guess they changed disc or something, handle that gracefully and get to root */
409 working
= SetCurrentDirectory(str
);
412 if (!working
) ConErrResPuts (STRING_FREE_ERROR1
);
422 /* get the PATH environment variable and parse it */
423 /* search the PATH environment variable for the binary */
424 if (!SearchForExecutable (first
, szFullName
))
426 error_bad_command ();
435 GetConsoleTitle (szWindowTitle
, MAX_PATH
);
437 /* check if this is a .BAT or .CMD file */
438 dot
= _tcsrchr (szFullName
, _T('.'));
439 if (dot
&& (!_tcsicmp (dot
, _T(".bat")) || !_tcsicmp (dot
, _T(".cmd"))))
442 DebugPrintf (_T("[BATCH: %s %s]\n"), szFullName
, rest
);
444 Batch (szFullName
, first
, rest
);
448 /* exec the program */
449 PROCESS_INFORMATION prci
;
453 DebugPrintf (_T("[EXEC: %s %s]\n"), full
, rest
);
455 /* build command line for CreateProcess() */
457 /* fill startup info */
458 memset (&stui
, 0, sizeof (STARTUPINFO
));
459 stui
.cb
= sizeof (STARTUPINFO
);
460 stui
.dwFlags
= STARTF_USESHOWWINDOW
;
461 stui
.wShowWindow
= SW_SHOWDEFAULT
;
463 // return console to standard mode
464 SetConsoleMode (GetStdHandle(STD_INPUT_HANDLE
),
465 ENABLE_LINE_INPUT
| ENABLE_PROCESSED_INPUT
| ENABLE_ECHO_INPUT
);
467 if (CreateProcess (szFullName
,
472 0, /* CREATE_NEW_PROCESS_GROUP */
479 if (IsConsoleProcess(prci
.hProcess
))
481 /* FIXME: Protect this with critical section */
482 bChildProcessRunning
= TRUE
;
483 dwChildProcessId
= prci
.dwProcessId
;
485 WaitForSingleObject (prci
.hProcess
, INFINITE
);
487 /* FIXME: Protect this with critical section */
488 bChildProcessRunning
= FALSE
;
490 GetExitCodeProcess (prci
.hProcess
, &dwExitCode
);
491 nErrorLevel
= (INT
)dwExitCode
;
493 CloseHandle (prci
.hThread
);
494 CloseHandle (prci
.hProcess
);
499 DebugPrintf (_T("[ShellExecute: %s]\n"), full
);
501 // See if we can run this with ShellExecute() ie myfile.xls
505 DebugPrintf (_T("[ShellExecute failed!: %s]\n"), full
);
507 error_bad_command ();
510 // restore console mode
512 GetStdHandle( STD_INPUT_HANDLE
),
513 ENABLE_PROCESSED_INPUT
);
516 /* Get code page if it has been change */
517 InputCodePage
= GetConsoleCP();
518 OutputCodePage
= GetConsoleOutputCP();
519 SetConsoleTitle (szWindowTitle
);
529 * look through the internal commands and determine whether or not this
530 * command is one of them. If it is, call the command. If not, call
531 * execute to run it as an external program.
533 * line - the command line of the program to run
538 DoCommand (LPTSTR line
)
540 TCHAR
*com
= NULL
; /* the first word in the command */
543 LPTSTR rest
; /* pointer to the rest of the command line */
548 DebugPrintf (_T("DoCommand: (\'%s\')\n"), line
);
551 com
= malloc( (_tcslen(line
) +512)*sizeof(TCHAR
) );
554 error_out_of_memory();
559 /* Skip over initial white space */
560 while (_istspace (*line
))
566 /* Anything to do ? */
569 if (*rest
== _T('"'))
571 /* treat quoted words specially */
575 while(*rest
!= _T('\0') && *rest
!= _T('"'))
576 *cp
++ = _totlower (*rest
++);
577 if (*rest
== _T('"'))
582 while (!IsDelimiter (*rest
))
583 *cp
++ = _totlower (*rest
++);
587 /* Terminate first word */
590 /* Do not limit commands to MAX_PATH */
592 if(_tcslen(com) > MAX_PATH)
600 /* Skip over whitespace to rest of line */
601 while (_istspace (*rest
))
604 /* Scan internal command table */
605 for (cmdptr
= cmds
;; cmdptr
++)
607 /* If end of table execute ext cmd */
608 if (cmdptr
->name
== NULL
)
610 Execute (line
, com
, rest
);
614 if (!_tcscmp (com
, cmdptr
->name
))
616 cmdptr
->func (com
, rest
);
620 /* The following code handles the case of commands like CD which
621 * are recognised even when the command name and parameter are
622 * not space separated.
628 /* Get length of command name */
629 cl
= _tcslen (cmdptr
->name
);
631 if ((cmdptr
->flags
& CMD_SPECIAL
) &&
632 (!_tcsncmp (cmdptr
->name
, com
, cl
)) &&
633 (_tcschr (_T("\\.-"), *(com
+ cl
))))
635 /* OK its one of the specials...*/
637 /* Terminate first word properly */
640 /* Call with new rest */
641 cmdptr
->func (com
, cstart
+ cl
);
646 /* Just in case a CTRL+C slipped through a command */
653 * process the command line and execute the appropriate functions
654 * full input/output redirection and piping are supported
657 VOID
ParseCommandLine (LPTSTR cmd
)
659 TCHAR szMsg
[RC_STRING_MAX_SIZE
];
660 TCHAR cmdline
[CMDLINE_LENGTH
];
662 #ifdef FEATURE_REDIRECTION
663 TCHAR in
[CMDLINE_LENGTH
] = _T("");
664 TCHAR out
[CMDLINE_LENGTH
] = _T("");
665 TCHAR err
[CMDLINE_LENGTH
] = _T("");
666 TCHAR szTempPath
[MAX_PATH
] = _T(".\\");
667 TCHAR szFileName
[2][MAX_PATH
] = {_T(""), _T("")};
668 HANDLE hFile
[2] = {INVALID_HANDLE_VALUE
, INVALID_HANDLE_VALUE
};
674 BOOL bNewBatch
= TRUE
;
678 #endif /* FEATURE_REDIRECTION */
680 _tcscpy (cmdline
, cmd
);
684 DebugPrintf (_T("ParseCommandLine: (\'%s\')\n"), s
);
687 #ifdef FEATURE_ALIASES
688 /* expand all aliases */
689 ExpandAlias (s
, CMDLINE_LENGTH
);
690 #endif /* FEATURE_ALIAS */
692 #ifdef FEATURE_REDIRECTION
693 /* find the temp path to store temporary files */
694 Length
= GetTempPath (MAX_PATH
, szTempPath
);
695 if (Length
> 0 && Length
< MAX_PATH
)
697 Attributes
= GetFileAttributes(szTempPath
);
698 if (Attributes
== 0xffffffff ||
699 !(Attributes
& FILE_ATTRIBUTE_DIRECTORY
))
704 if (Length
== 0 || Length
>= MAX_PATH
)
706 _tcscpy(szTempPath
, _T(".\\"));
708 if (szTempPath
[_tcslen (szTempPath
) - 1] != _T('\\'))
709 _tcscat (szTempPath
, _T("\\"));
711 /* get the redirections from the command line */
712 num
= GetRedirection (s
, in
, out
, err
, &nRedirFlags
);
714 /* more efficient, but do we really need to do this? */
715 for (t
= in
; _istspace (*t
); t
++)
719 for (t
= out
; _istspace (*t
); t
++)
723 for (t
= err
; _istspace (*t
); t
++)
727 if(bc
&& !_tcslen (in
) && _tcslen (bc
->In
))
729 if(bc
&& !out
[0] && _tcslen(bc
->Out
))
731 nRedirFlags
|= OUTPUT_APPEND
;
732 _tcscpy(out
, bc
->Out
);
734 if(bc
&& !_tcslen (err
) && _tcslen (bc
->Err
))
736 nRedirFlags
|= ERROR_APPEND
;
737 _tcscpy(err
, bc
->Err
);
741 /* Set up the initial conditions ... */
742 /* preserve STDIN, STDOUT and STDERR handles */
743 hOldConIn
= GetStdHandle (STD_INPUT_HANDLE
);
744 hOldConOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
745 hOldConErr
= GetStdHandle (STD_ERROR_HANDLE
);
751 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
753 /* we need make sure the LastError msg is zero before calling CreateFile */
756 /* Set up pipe for the standard input handler */
757 hFile
= CreateFile (in
, GENERIC_READ
, FILE_SHARE_READ
, &sa
, OPEN_EXISTING
,
758 FILE_ATTRIBUTE_NORMAL
, NULL
);
759 if (hFile
== INVALID_HANDLE_VALUE
)
761 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR1
, szMsg
, RC_STRING_MAX_SIZE
);
762 ConErrPrintf(szMsg
, in
);
766 if (!SetStdHandle (STD_INPUT_HANDLE
, hFile
))
768 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR1
, szMsg
, RC_STRING_MAX_SIZE
);
769 ConErrPrintf(szMsg
, in
);
773 DebugPrintf (_T("Input redirected from: %s\n"), in
);
777 /* Now do all but the last pipe command */
778 *szFileName
[0] = _T('\0');
779 hFile
[0] = INVALID_HANDLE_VALUE
;
783 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
785 /* Create unique temporary file name */
786 GetTempFileName (szTempPath
, _T("CMD"), 0, szFileName
[1]);
788 /* we need make sure the LastError msg is zero before calling CreateFile */
791 /* Set current stdout to temporary file */
792 hFile
[1] = CreateFile (szFileName
[1], GENERIC_WRITE
, 0, &sa
,
793 TRUNCATE_EXISTING
, FILE_ATTRIBUTE_TEMPORARY
, NULL
);
795 if (hFile
[1] == INVALID_HANDLE_VALUE
)
797 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR2
, szMsg
, RC_STRING_MAX_SIZE
);
802 SetStdHandle (STD_OUTPUT_HANDLE
, hFile
[1]);
806 /* close stdout file */
807 SetStdHandle (STD_OUTPUT_HANDLE
, hOldConOut
);
808 if ((hFile
[1] != INVALID_HANDLE_VALUE
) && (hFile
[1] != hOldConOut
))
810 CloseHandle (hFile
[1]);
811 hFile
[1] = INVALID_HANDLE_VALUE
;
814 /* close old stdin file */
815 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
816 if ((hFile
[0] != INVALID_HANDLE_VALUE
) && (hFile
[0] != hOldConIn
))
818 /* delete old stdin file, if it is a real file */
819 CloseHandle (hFile
[0]);
820 hFile
[0] = INVALID_HANDLE_VALUE
;
821 DeleteFile (szFileName
[0]);
822 *szFileName
[0] = _T('\0');
825 /* copy stdout file name to stdin file name */
826 _tcscpy (szFileName
[0], szFileName
[1]);
827 *szFileName
[1] = _T('\0');
829 /* we need make sure the LastError msg is zero before calling CreateFile */
832 /* open new stdin file */
833 hFile
[0] = CreateFile (szFileName
[0], GENERIC_READ
, 0, &sa
,
834 OPEN_EXISTING
, FILE_ATTRIBUTE_TEMPORARY
, NULL
);
835 SetStdHandle (STD_INPUT_HANDLE
, hFile
[0]);
837 s
= s
+ _tcslen (s
) + 1;
840 /* Now set up the end conditions... */
841 /* redirect STDOUT */
844 /* Final output to here */
846 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
848 /* we need make sure the LastError msg is zero before calling CreateFile */
851 hFile
= CreateFile (out
, GENERIC_WRITE
, FILE_SHARE_WRITE
| FILE_SHARE_READ
| FILE_SHARE_DELETE
, &sa
,
852 (nRedirFlags
& OUTPUT_APPEND
) ? OPEN_ALWAYS
: CREATE_ALWAYS
,
853 FILE_ATTRIBUTE_NORMAL
| FILE_FLAG_WRITE_THROUGH
, NULL
);
855 if (hFile
== INVALID_HANDLE_VALUE
)
857 INT size
= _tcslen(out
)-1;
859 if (out
[size
] != _T(':'))
861 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR3
, szMsg
, RC_STRING_MAX_SIZE
);
862 ConErrPrintf(szMsg
, out
);
867 hFile
= CreateFile (out
, GENERIC_WRITE
, FILE_SHARE_WRITE
| FILE_SHARE_READ
| FILE_SHARE_DELETE
, &sa
,
868 (nRedirFlags
& OUTPUT_APPEND
) ? OPEN_ALWAYS
: CREATE_ALWAYS
,
869 FILE_ATTRIBUTE_NORMAL
| FILE_FLAG_WRITE_THROUGH
, NULL
);
871 if (hFile
== INVALID_HANDLE_VALUE
)
873 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR3
, szMsg
, RC_STRING_MAX_SIZE
);
874 ConErrPrintf(szMsg
, out
);
880 if (!SetStdHandle (STD_OUTPUT_HANDLE
, hFile
))
882 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR3
, szMsg
, RC_STRING_MAX_SIZE
);
883 ConErrPrintf(szMsg
, out
);
887 if (nRedirFlags
& OUTPUT_APPEND
)
891 if (GetFileType (hFile
) == FILE_TYPE_DISK
)
892 SetFilePointer (hFile
, 0, &lHighPos
, FILE_END
);
895 DebugPrintf (_T("Output redirected to: %s\n"), out
);
898 else if (hOldConOut
!= INVALID_HANDLE_VALUE
)
900 /* Restore original stdout */
901 HANDLE hOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
902 SetStdHandle (STD_OUTPUT_HANDLE
, hOldConOut
);
903 if (hOldConOut
!= hOut
)
905 hOldConOut
= INVALID_HANDLE_VALUE
;
908 /* redirect STDERR */
911 /* Final output to here */
913 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
915 if (!_tcscmp (err
, out
))
918 DebugPrintf (_T("Stdout and stderr will use the same file!!\n"));
920 DuplicateHandle (GetCurrentProcess (),
921 GetStdHandle (STD_OUTPUT_HANDLE
),
922 GetCurrentProcess (),
923 &hFile
, 0, TRUE
, DUPLICATE_SAME_ACCESS
);
927 hFile
= CreateFile (err
,
929 FILE_SHARE_WRITE
| FILE_SHARE_READ
| FILE_SHARE_DELETE
,
931 (nRedirFlags
& ERROR_APPEND
) ? OPEN_ALWAYS
: CREATE_ALWAYS
,
932 FILE_ATTRIBUTE_NORMAL
| FILE_FLAG_WRITE_THROUGH
,
934 if (hFile
== INVALID_HANDLE_VALUE
)
936 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR3
, szMsg
, RC_STRING_MAX_SIZE
);
937 ConErrPrintf(szMsg
, err
);
942 if (!SetStdHandle (STD_ERROR_HANDLE
, hFile
))
944 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR3
, szMsg
, RC_STRING_MAX_SIZE
);
945 ConErrPrintf(szMsg
, err
);
949 if (nRedirFlags
& ERROR_APPEND
)
953 if (GetFileType (hFile
) == FILE_TYPE_DISK
)
954 SetFilePointer (hFile
, 0, &lHighPos
, FILE_END
);
957 DebugPrintf (_T("Error redirected to: %s\n"), err
);
960 else if (hOldConErr
!= INVALID_HANDLE_VALUE
)
962 /* Restore original stderr */
963 HANDLE hErr
= GetStdHandle (STD_ERROR_HANDLE
);
964 SetStdHandle (STD_ERROR_HANDLE
, hOldConErr
);
965 if (hOldConErr
!= hErr
)
967 hOldConErr
= INVALID_HANDLE_VALUE
;
974 /* process final command */
977 #ifdef FEATURE_REDIRECTION
979 AddBatchRedirection(in
, out
, err
);
980 /* close old stdin file */
981 #if 0 /* buggy implementation */
982 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
983 if ((hFile
[0] != INVALID_HANDLE_VALUE
) &&
984 (hFile
[0] != hOldConIn
))
986 /* delete old stdin file, if it is a real file */
987 CloseHandle (hFile
[0]);
988 hFile
[0] = INVALID_HANDLE_VALUE
;
989 DeleteFile (szFileName
[0]);
990 *szFileName
[0] = _T('\0');
993 /* Restore original STDIN */
994 if (hOldConIn
!= INVALID_HANDLE_VALUE
)
996 HANDLE hIn
= GetStdHandle (STD_INPUT_HANDLE
);
997 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
998 if (hOldConIn
!= hIn
)
1000 hOldConIn
= INVALID_HANDLE_VALUE
;
1005 DebugPrintf (_T("Can't restore STDIN! Is invalid!!\n"), out
);
1008 #endif /* buggy implementation */
1011 if (hOldConIn
!= INVALID_HANDLE_VALUE
)
1013 HANDLE hIn
= GetStdHandle (STD_INPUT_HANDLE
);
1014 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
1015 if (hIn
== INVALID_HANDLE_VALUE
)
1018 DebugPrintf (_T("Previous STDIN is invalid!!\n"));
1023 if (GetFileType (hIn
) == FILE_TYPE_DISK
)
1025 if (hFile
[0] == hIn
)
1027 CloseHandle (hFile
[0]);
1028 hFile
[0] = INVALID_HANDLE_VALUE
;
1029 DeleteFile (szFileName
[0]);
1030 *szFileName
[0] = _T('\0');
1035 DebugPrintf (_T("hFile[0] and hIn dont match!!!\n"));
1043 /* Restore original STDOUT */
1044 if (hOldConOut
!= INVALID_HANDLE_VALUE
)
1046 HANDLE hOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
1047 SetStdHandle (STD_OUTPUT_HANDLE
, hOldConOut
);
1048 if (hOldConOut
!= hOut
)
1050 hOldConOut
= INVALID_HANDLE_VALUE
;
1053 /* Restore original STDERR */
1054 if (hOldConErr
!= INVALID_HANDLE_VALUE
)
1056 HANDLE hErr
= GetStdHandle (STD_ERROR_HANDLE
);
1057 SetStdHandle (STD_ERROR_HANDLE
, hOldConErr
);
1058 if (hOldConErr
!= hErr
)
1060 hOldConErr
= INVALID_HANDLE_VALUE
;
1062 #endif /* FEATURE_REDIRECTION */
1066 GrowIfNecessary ( UINT needed
, LPTSTR
* ret
, UINT
* retlen
)
1068 if ( *ret
&& needed
< *retlen
)
1073 *ret
= (LPTSTR
)malloc ( *retlen
* sizeof(TCHAR
) );
1075 SetLastError ( ERROR_OUTOFMEMORY
);
1076 return *ret
!= NULL
;
1080 GetEnvVarOrSpecial ( LPCTSTR varName
)
1082 static LPTSTR ret
= NULL
;
1083 static UINT retlen
= 0;
1086 size
= GetEnvironmentVariable ( varName
, ret
, retlen
);
1087 if ( size
> retlen
)
1089 if ( !GrowIfNecessary ( size
, &ret
, &retlen
) )
1091 size
= GetEnvironmentVariable ( varName
, ret
, retlen
);
1096 /* env var doesn't exist, look for a "special" one */
1098 if (_tcsicmp(varName
,_T("cd")) ==0)
1100 size
= GetCurrentDirectory ( retlen
, ret
);
1101 if ( size
> retlen
)
1103 if ( !GrowIfNecessary ( size
, &ret
, &retlen
) )
1105 size
= GetCurrentDirectory ( retlen
, ret
);
1112 else if (_tcsicmp(varName
,_T("time")) ==0)
1115 if ( !GrowIfNecessary ( MAX_PATH
, &ret
, &retlen
) )
1118 _sntprintf ( ret
, retlen
, _T("%02d%c%02d%c%02d%c%02d"),
1119 t
.wHour
, cTimeSeparator
, t
.wMinute
, cTimeSeparator
,
1120 t
.wSecond
, cDecimalSeparator
, t
.wMilliseconds
);
1124 else if (_tcsicmp(varName
,_T("date")) ==0)
1128 if ( !GrowIfNecessary ( MAX_PATH
, &ret
, &retlen
) )
1130 size
= GetDateFormat(LOCALE_USER_DEFAULT
, 0, NULL
, _T("ddd"), ret
, retlen
);
1131 /* TODO FIXME - test whether GetDateFormat() can return a value indicating the buffer wasn't big enough */
1134 tmp
= ret
+ _tcslen(ret
);
1136 size
= GetDateFormat(LOCALE_USER_DEFAULT
, DATE_SHORTDATE
, NULL
, NULL
, tmp
, retlen
-(tmp
-ret
));
1137 /* TODO FIXME - test whether GetDateFormat() can return a value indicating the buffer wasn't big enough */
1144 else if (_tcsicmp(varName
,_T("random")) ==0)
1146 if ( !GrowIfNecessary ( MAX_PATH
, &ret
, &retlen
) )
1148 /* Get random number */
1149 _itot(rand(),ret
,10);
1154 else if (_tcsicmp(varName
,_T("cmdcmdline")) ==0)
1156 return GetCommandLine();
1159 /* %CMDEXTVERSION% */
1160 else if (_tcsicmp(varName
,_T("cmdextversion")) ==0)
1162 if ( !GrowIfNecessary ( MAX_PATH
, &ret
, &retlen
) )
1164 /* Set version number to 2 */
1170 else if (_tcsicmp(varName
,_T("errorlevel")) ==0)
1172 if ( !GrowIfNecessary ( MAX_PATH
, &ret
, &retlen
) )
1174 _itot(nErrorLevel
,ret
,10);
1178 GrowIfNecessary(_tcslen(varName
) + 2, &ret
, &retlen
);
1179 _stprintf(ret
,_T("%%%s%%"),varName
);
1180 return ret
; /* not found - return orginal string */
1184 GetParsedEnvVar ( LPCTSTR varName
, UINT
* varNameLen
, BOOL ModeSetA
)
1186 static LPTSTR ret
= NULL
;
1187 static UINT retlen
= 0;
1194 if ( *varName
++ != '%' )
1208 if ((tmp
= FindArg (*varName
- _T('0'))))
1214 if ( !GrowIfNecessary ( _tcslen(tmp
)+1, &ret
, &retlen
) )
1216 _tcscpy ( ret
, tmp
);
1219 if ( !GrowIfNecessary ( 3, &ret
, &retlen
) )
1229 if ( !GrowIfNecessary ( 2, &ret
, &retlen
) )
1238 /* TODO FIXME 10 is only max size for 32-bit */
1239 if ( !GrowIfNecessary ( 11, &ret
, &retlen
) )
1241 _sntprintf ( ret
, retlen
, _T("%u"), nErrorLevel
);
1249 /* HACK for set/a */
1250 if ( !GrowIfNecessary ( 2, &ret
, &retlen
) )
1258 p
= _tcschr ( varName
, _T('%') );
1261 SetLastError ( ERROR_INVALID_PARAMETER
);
1266 *varNameLen
= size
+ 2;
1267 p
= alloca ( (size
+1) * sizeof(TCHAR
) );
1268 memmove ( p
, varName
, size
* sizeof(TCHAR
) );
1271 return GetEnvVarOrSpecial ( varName
);
1276 * do the prompt/input/process loop
1281 ProcessInput (BOOL bFlag
)
1283 TCHAR commandline
[CMDLINE_LENGTH
];
1284 TCHAR readline
[CMDLINE_LENGTH
];
1294 /* if no batch input then... */
1295 if (!(ip
= ReadBatchLine (&bEchoThisLine
)))
1300 ReadCommand (readline
, CMDLINE_LENGTH
);
1302 bEchoThisLine
= FALSE
;
1310 /* skip leading blanks */
1311 while ( _istspace(*ip
) )
1318 if ( *ip
== _T('%') )
1321 LPCTSTR envVal
= GetParsedEnvVar ( ip
, &envNameLen
, bModeSetA
);
1325 cp
= _stpcpy ( cp
, envVal
);
1329 if (_istcntrl (*ip
))
1333 /* HACK HACK HACK check whether bModeSetA needs to be toggled */
1336 tmp
+= _tcsspn(tmp
,_T(" \t"));
1337 /* first we find and skip and pre-redirections... */
1338 while ( _tcschr(_T("<>"),*tmp
)
1339 || !_tcsncmp(tmp
,_T("1>"),2)
1340 || !_tcsncmp(tmp
,_T("2>"),2) )
1342 if ( _istdigit(*tmp
) )
1346 tmp
+= _tcsspn(tmp
,_T(" \t"));
1347 if ( *tmp
== _T('\"') )
1349 tmp
= _tcschr(tmp
+1,_T('\"'));
1354 tmp
= _tcspbrk(tmp
,_T(" \t"));
1355 tmp
+= _tcsspn(tmp
,_T(" \t"));
1357 /* we should now be pointing to the actual command
1358 * (if there is one yet)*/
1361 /* if we're currently substituting ( which is default )
1362 * check to see if we've parsed out a set/a. if so, we
1363 * need to disable substitution until we come across a
1367 /* look for set /a */
1368 if ( !_tcsnicmp(tmp
,_T("set"),3) )
1371 tmp
+= _tcsspn(tmp
,_T(" \t"));
1372 if ( !_tcsnicmp(tmp
,_T("/a"),2) )
1376 /* if we're not currently substituting, it means we're
1377 * already inside a set /a. now we need to look for
1378 * a redirection in order to turn redirection back on */
1381 /* look for redirector of some kind after the command */
1382 while ( (tmp
= _tcspbrk ( tmp
, _T("^<>|") )) )
1384 if ( *tmp
== _T('^') )
1386 if ( _tcschr(_T("<>|&"), *++tmp
) && *tmp
)
1401 /* strip trailing spaces */
1402 while ((--cp
>= commandline
) && _istspace (*cp
));
1404 *(cp
+ 1) = _T('\0');
1407 /* Echo batch file line */
1411 ConOutPuts (commandline
);
1416 ParseCommandLine (commandline
);
1417 if (bEcho
&& !bIgnoreEcho
&& (!bIsBatch
|| bEchoThisLine
))
1419 bIgnoreEcho
= FALSE
;
1422 while (!bCanExit
|| !bExit
);
1429 * control-break handler.
1431 BOOL WINAPI
BreakHandler (DWORD dwCtrlType
)
1434 static BOOL SelfGenerated
= FALSE
;
1436 if ((dwCtrlType
!= CTRL_C_EVENT
) &&
1437 (dwCtrlType
!= CTRL_BREAK_EVENT
))
1445 SelfGenerated
= FALSE
;
1450 if (bChildProcessRunning
== TRUE
)
1452 SelfGenerated
= TRUE
;
1453 GenerateConsoleCtrlEvent (dwCtrlType
, 0);
1458 /* FIXME: Handle batch files */
1460 //ConOutPrintf(_T("^C"));
1467 VOID
AddBreakHandler (VOID
)
1469 SetConsoleCtrlHandler ((PHANDLER_ROUTINE
)BreakHandler
, TRUE
);
1473 VOID
RemoveBreakHandler (VOID
)
1475 SetConsoleCtrlHandler ((PHANDLER_ROUTINE
)BreakHandler
, FALSE
);
1480 * show commands and options that are available.
1487 /* print command list */
1488 ConOutResPuts(STRING_CMD_HELP1
);
1491 /* print feature list */
1492 ConOutResPuts(STRING_CMD_HELP2
);
1494 #ifdef FEATURE_ALIASES
1495 ConOutResPuts(STRING_CMD_HELP3
);
1497 #ifdef FEATURE_HISTORY
1498 ConOutResPuts(STRING_CMD_HELP4
);
1500 #ifdef FEATURE_UNIX_FILENAME_COMPLETION
1501 ConOutResPuts(STRING_CMD_HELP5
);
1503 #ifdef FEATURE_DIRECTORY_STACK
1504 ConOutResPuts(STRING_CMD_HELP6
);
1506 #ifdef FEATURE_REDIRECTION
1507 ConOutResPuts(STRING_CMD_HELP7
);
1509 ConOutChar(_T('\n'));
1514 * set up global initializations and process parameters
1516 * argc - number of parameters to command.com
1517 * argv - command-line parameters
1521 Initialize (int argc
, TCHAR
* argv
[])
1523 TCHAR commandline
[CMDLINE_LENGTH
];
1524 TCHAR ModuleName
[_MAX_PATH
+ 1];
1529 //TCHAR *ptr, *cmdLine;
1531 /* get version information */
1532 osvi
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
1533 GetVersionEx (&osvi
);
1535 /* Some people like to run ReactOS cmd.exe on Win98, it helps in the
1536 * build process. So don't link implicitly against ntdll.dll, load it
1537 * dynamically instead */
1539 if (osvi
.dwPlatformId
== VER_PLATFORM_WIN32_NT
)
1541 /* ntdll is always present on NT */
1542 NtDllModule
= GetModuleHandle(TEXT("ntdll.dll"));
1546 /* not all 9x versions have a ntdll.dll, try to load it */
1547 NtDllModule
= LoadLibrary(TEXT("ntdll.dll"));
1550 if (NtDllModule
!= NULL
)
1552 NtQueryInformationProcessPtr
= (NtQueryInformationProcessProc
)GetProcAddress(NtDllModule
, "NtQueryInformationProcess");
1553 NtReadVirtualMemoryPtr
= (NtReadVirtualMemoryProc
)GetProcAddress(NtDllModule
, "NtReadVirtualMemory");
1558 DebugPrintf (_T("[command args:\n"));
1559 for (i
= 0; i
< argc
; i
++)
1561 DebugPrintf (_T("%d. %s\n"), i
, argv
[i
]);
1563 DebugPrintf (_T("]\n"));
1568 /* get default input and output console handles */
1569 hOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
1570 hIn
= GetStdHandle (STD_INPUT_HANDLE
);
1572 /* Set EnvironmentVariable PROMPT if it does not exists any env value.
1573 for you can change the EnvirommentVariable for prompt before cmd start
1574 this patch are not 100% right, if it does not exists a PROMPT value cmd should use
1575 $P$G as defualt not set EnvirommentVariable PROMPT to $P$G if it does not exists */
1576 if (GetEnvironmentVariable(_T("PROMPT"),lpBuffer
, sizeof(lpBuffer
) / sizeof(lpBuffer
[0])) == 0)
1577 SetEnvironmentVariable (_T("PROMPT"), _T("$P$G"));
1580 if (argc
>= 2 && !_tcsncmp (argv
[1], _T("/?"), 2))
1582 ConOutResPaging(TRUE
,STRING_CMD_HELP8
);
1585 SetConsoleMode (hIn
, ENABLE_PROCESSED_INPUT
);
1587 #ifdef INCLUDE_CMD_CHDIR
1591 #ifdef FATURE_ALIASES
1597 for (i
= 1; i
< argc
; i
++)
1599 if (!_tcsicmp (argv
[i
], _T("/p")))
1601 if (!IsExistingFile (_T("\\autoexec.bat")))
1603 #ifdef INCLUDE_CMD_DATE
1604 cmd_date (_T(""), _T(""));
1606 #ifdef INCLUDE_CMD_TIME
1607 cmd_time (_T(""), _T(""));
1612 ParseCommandLine (_T("\\autoexec.bat"));
1616 else if (!_tcsicmp (argv
[i
], _T("/c")))
1618 /* This just runs a program and exits */
1622 _tcscpy (commandline
, argv
[i
]);
1625 _tcscat (commandline
, _T(" "));
1626 _tcscat (commandline
, argv
[i
]);
1629 ParseCommandLine(commandline
);
1630 ExitProcess (ProcessInput (TRUE
));
1637 else if (!_tcsicmp (argv
[i
], _T("/k")))
1639 /* This just runs a program and remains */
1643 _tcscpy (commandline
, _T("\""));
1644 _tcscat (commandline
, argv
[i
]);
1645 _tcscat (commandline
, _T("\""));
1648 _tcscat (commandline
, _T(" "));
1649 _tcscat (commandline
, argv
[i
]);
1651 ParseCommandLine(commandline
);
1654 #ifdef INCLUDE_CMD_COLOR
1655 else if (!_tcsnicmp (argv
[i
], _T("/t:"), 3))
1657 /* process /t (color) argument */
1658 wDefColor
= (WORD
)_tcstoul (&argv
[i
][3], NULL
, 16);
1660 SetScreenColor (wColor
, TRUE
);
1666 /* run cmdstart.bat */
1667 if (IsExistingFile (_T("cmdstart.bat")))
1669 ParseCommandLine (_T("cmdstart.bat"));
1671 else if (IsExistingFile (_T("\\cmdstart.bat")))
1673 ParseCommandLine (_T("\\cmdstart.bat"));
1676 #ifdef FEATURE_DIR_STACK
1677 /* initialize directory stack */
1678 InitDirectoryStack ();
1682 #ifdef FEATURE_HISTORY
1683 /*initialize history*/
1687 /* Set COMSPEC environment variable */
1688 if (0 != GetModuleFileName (NULL
, ModuleName
, _MAX_PATH
+ 1))
1690 ModuleName
[_MAX_PATH
] = _T('\0');
1691 SetEnvironmentVariable (_T("COMSPEC"), ModuleName
);
1694 /* add ctrl break handler */
1699 static VOID
Cleanup (int argc
, TCHAR
*argv
[])
1701 /* run cmdexit.bat */
1702 if (IsExistingFile (_T("cmdexit.bat")))
1704 ConErrResPuts(STRING_CMD_ERROR5
);
1706 ParseCommandLine (_T("cmdexit.bat"));
1708 else if (IsExistingFile (_T("\\cmdexit.bat")))
1710 ConErrResPuts (STRING_CMD_ERROR5
);
1711 ParseCommandLine (_T("\\cmdexit.bat"));
1714 #ifdef FEATURE_ALIASES
1718 #ifdef FEATURE_DIECTORY_STACK
1719 /* destroy directory stack */
1720 DestroyDirectoryStack ();
1723 #ifdef INCLUDE_CMD_CHDIR
1727 #ifdef FEATURE_HISTORY
1732 /* remove ctrl break handler */
1733 RemoveBreakHandler ();
1734 SetConsoleMode( GetStdHandle( STD_INPUT_HANDLE
),
1735 ENABLE_LINE_INPUT
| ENABLE_PROCESSED_INPUT
| ENABLE_ECHO_INPUT
);
1737 if (NtDllModule
!= NULL
)
1739 FreeLibrary(NtDllModule
);
1749 int _main (int argc
, char *argv
[])
1752 TCHAR startPath
[MAX_PATH
];
1753 CONSOLE_SCREEN_BUFFER_INFO Info
;
1758 argv
= CommandLineToArgvW(GetCommandLineW(), &argc
);
1761 GetCurrentDirectory(MAX_PATH
,startPath
);
1768 hConsole
= CreateFile(_T("CONOUT$"), GENERIC_READ
|GENERIC_WRITE
,
1769 FILE_SHARE_READ
|FILE_SHARE_WRITE
, NULL
,
1770 OPEN_EXISTING
, 0, NULL
);
1771 if (GetConsoleScreenBufferInfo(hConsole
, &Info
) == FALSE
)
1773 ConErrFormatMessage(GetLastError());
1776 wColor
= Info
.wAttributes
;
1779 InputCodePage
= GetConsoleCP();
1780 OutputCodePage
= GetConsoleOutputCP();
1781 CMD_ModuleHandle
= GetModuleHandle(NULL
);
1783 /* check switches on command-line */
1784 Initialize(argc
, argv
);
1786 /* call prompt routine */
1787 nExitCode
= ProcessInput(FALSE
);
1789 /* do the cleanup */
1790 Cleanup(argc
, argv
);