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 (STDCALL
*NtQueryInformationProcessProc
)(HANDLE
, PROCESSINFOCLASS
,
152 PVOID
, ULONG
, PULONG
);
153 typedef NTSTATUS (STDCALL
*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(Process
, ProcessBasicInformation
,
203 &Info
, sizeof(PROCESS_BASIC_INFORMATION
), NULL
);
204 if (! NT_SUCCESS(Status
))
207 DebugPrintf (_T("NtQueryInformationProcess failed with status %08x\n"), Status
);
211 Status
= NtReadVirtualMemoryPtr(Process
, Info
.PebBaseAddress
, &ProcessPeb
,
212 sizeof(PEB
), &BytesRead
);
213 if (! NT_SUCCESS(Status
) || sizeof(PEB
) != BytesRead
)
216 DebugPrintf (_T("Couldn't read virt mem status %08x bytes read %lu\n"), Status
, BytesRead
);
221 return IMAGE_SUBSYSTEM_WINDOWS_CUI
== ProcessPeb
.ImageSubSystem
;
227 #define SHELLEXECUTETEXT "ShellExecuteW"
229 #define SHELLEXECUTETEXT "ShellExecuteA"
232 typedef HINSTANCE (WINAPI
*MYEX
)(
236 LPCTSTR lpParameters
,
243 static BOOL
RunFile(LPTSTR filename
)
250 DebugPrintf (_T("RunFile(%s)\n"), filename
);
252 hShell32
= LoadLibrary(_T("SHELL32.DLL"));
256 DebugPrintf (_T("RunFile: couldn't load SHELL32.DLL!\n"));
261 hShExt
= (MYEX
)(FARPROC
)GetProcAddress(hShell32
, SHELLEXECUTETEXT
);
265 DebugPrintf (_T("RunFile: couldn't find ShellExecuteA/W in SHELL32.DLL!\n"));
267 FreeLibrary(hShell32
);
272 DebugPrintf (_T("RunFile: ShellExecuteA/W is at %x\n"), hShExt
);
275 ret
= (hShExt
)(NULL
, _T("open"), filename
, NULL
, NULL
, SW_SHOWNORMAL
);
278 DebugPrintf (_T("RunFile: ShellExecuteA/W returned %d\n"), (DWORD
)ret
);
281 FreeLibrary(hShell32
);
282 return (((DWORD
)ret
) > 32);
288 * This command (in first) was not found in the command table
290 * Full - whole command line
291 * First - first word on command line
292 * Rest - rest of command line
296 Execute (LPTSTR Full
, LPTSTR First
, LPTSTR Rest
)
298 TCHAR szFullName
[MAX_PATH
];
303 TCHAR szWindowTitle
[MAX_PATH
];
305 DWORD dwExitCode
= 0;
308 DebugPrintf (_T("Execute: \'%s\' \'%s\'\n"), first
, rest
);
311 /* we need biger buffer that First, Rest, Full are already
312 need rewrite some code to use realloc when it need instead
313 of add 512bytes extra */
315 first
= malloc ( _tcslen(First
) + 512 * sizeof(TCHAR
));
318 error_out_of_memory();
322 rest
= malloc ( _tcslen(Rest
) + 512 * sizeof(TCHAR
));
326 error_out_of_memory();
330 full
= malloc ( _tcslen(Full
) + 512 * sizeof(TCHAR
));
335 error_out_of_memory();
340 /* Though it was already parsed once, we have a different set of rules
341 for parsing before we pass to CreateProccess */
342 if(!_tcschr(Full
,_T('\"')))
344 _tcscpy(first
,First
);
351 BOOL bInside
= FALSE
;
356 /* find the end of the command and start of the args */
357 for(i
= 0; i
< _tcslen(first
); i
++)
359 if(!_tcsncmp(&first
[i
], _T("\""), 1))
361 if(!_tcsncmp(&first
[i
], _T(" "), 1) && !bInside
)
363 _tcscpy(rest
,&first
[i
]);
370 /* remove any slashes */
371 while(i
< _tcslen(first
))
373 if(first
[i
] == _T('\"'))
374 memmove(&first
[i
],&first
[i
+ 1], _tcslen(&first
[i
]) * sizeof(TCHAR
));
378 /* Drop quotes around it just in case there is a space */
379 _tcscpy(full
,_T("\""));
381 _tcscat(full
,_T("\" "));
385 /* check for a drive change */
386 if ((_istalpha (first
[0])) && (!_tcscmp (first
+ 1, _T(":"))))
389 if (!SetCurrentDirectory(first
))
390 /* Guess they changed disc or something, handle that gracefully and get to root */
397 working
= SetCurrentDirectory(str
);
400 if (!working
) ConErrResPuts (STRING_FREE_ERROR1
);
405 /* get the PATH environment variable and parse it */
406 /* search the PATH environment variable for the binary */
407 if (!SearchForExecutable (first
, szFullName
))
409 error_bad_command ();
414 GetConsoleTitle (szWindowTitle
, MAX_PATH
);
417 /* check if this is a .BAT or .CMD file */
418 if (!_tcsicmp (_tcsrchr (szFullName
, _T('.')), _T(".bat")) ||
419 !_tcsicmp (_tcsrchr (szFullName
, _T('.')), _T(".cmd")))
422 DebugPrintf (_T("[BATCH: %s %s]\n"), szFullName
, rest
);
424 Batch (szFullName
, first
, rest
);
428 /* exec the program */
429 PROCESS_INFORMATION prci
;
433 DebugPrintf (_T("[EXEC: %s %s]\n"), full
, rest
);
435 /* build command line for CreateProcess() */
437 /* fill startup info */
438 memset (&stui
, 0, sizeof (STARTUPINFO
));
439 stui
.cb
= sizeof (STARTUPINFO
);
440 stui
.dwFlags
= STARTF_USESHOWWINDOW
;
441 stui
.wShowWindow
= SW_SHOWDEFAULT
;
443 // return console to standard mode
444 SetConsoleMode (GetStdHandle(STD_INPUT_HANDLE
),
445 ENABLE_LINE_INPUT
| ENABLE_PROCESSED_INPUT
| ENABLE_ECHO_INPUT
);
447 if (CreateProcess (szFullName
,
452 CREATE_NEW_PROCESS_GROUP
,
458 if (IsConsoleProcess(prci
.hProcess
))
460 /* FIXME: Protect this with critical section */
461 bChildProcessRunning
= TRUE
;
462 dwChildProcessId
= prci
.dwProcessId
;
464 WaitForSingleObject (prci
.hProcess
, INFINITE
);
466 /* FIXME: Protect this with critical section */
467 bChildProcessRunning
= FALSE
;
469 GetExitCodeProcess (prci
.hProcess
, &dwExitCode
);
470 nErrorLevel
= (INT
)dwExitCode
;
472 CloseHandle (prci
.hThread
);
473 CloseHandle (prci
.hProcess
);
478 DebugPrintf (_T("[ShellExecute: %s]\n"), full
);
480 // See if we can run this with ShellExecute() ie myfile.xls
484 DebugPrintf (_T("[ShellExecute failed!: %s]\n"), full
);
486 error_bad_command ();
489 // restore console mode
490 SetConsoleMode( GetStdHandle( STD_INPUT_HANDLE
),
491 ENABLE_PROCESSED_INPUT
);
494 /* Get code page if it has been change */
495 InputCodePage
= GetConsoleCP();
496 OutputCodePage
= GetConsoleOutputCP();
498 SetConsoleTitle (szWindowTitle
);
508 * look through the internal commands and determine whether or not this
509 * command is one of them. If it is, call the command. If not, call
510 * execute to run it as an external program.
512 * line - the command line of the program to run
517 DoCommand (LPTSTR line
)
519 TCHAR com
[CMDLINE_LENGTH
]; /* the first word in the command */
522 LPTSTR rest
; /* pointer to the rest of the command line */
527 DebugPrintf (_T("DoCommand: (\'%s\')\n"), line
);
530 /* Skip over initial white space */
531 while (_istspace (*line
))
537 /* Anything to do ? */
540 if (*rest
== _T('"'))
542 /* treat quoted words specially */
546 while(*rest
!= _T('\0') && *rest
!= _T('"'))
547 *cp
++ = _totlower (*rest
++);
548 if (*rest
== _T('"'))
553 while (!IsDelimiter (*rest
))
554 *cp
++ = _totlower (*rest
++);
558 /* Terminate first word */
561 /* commands are limited to MAX_PATH */
562 if(_tcslen(com
) > MAX_PATH
)
568 /* Skip over whitespace to rest of line */
569 while (_istspace (*rest
))
572 /* Scan internal command table */
573 for (cmdptr
= cmds
;; cmdptr
++)
575 /* If end of table execute ext cmd */
576 if (cmdptr
->name
== NULL
)
578 Execute (line
, com
, rest
);
582 if (!_tcscmp (com
, cmdptr
->name
))
584 cmdptr
->func (com
, rest
);
588 /* The following code handles the case of commands like CD which
589 * are recognised even when the command name and parameter are
590 * not space separated.
596 /* Get length of command name */
597 cl
= _tcslen (cmdptr
->name
);
599 if ((cmdptr
->flags
& CMD_SPECIAL
) &&
600 (!_tcsncmp (cmdptr
->name
, com
, cl
)) &&
601 (_tcschr (_T("\\.-"), *(com
+ cl
))))
603 /* OK its one of the specials...*/
605 /* Terminate first word properly */
608 /* Call with new rest */
609 cmdptr
->func (com
, cstart
+ cl
);
618 * process the command line and execute the appropriate functions
619 * full input/output redirection and piping are supported
622 VOID
ParseCommandLine (LPTSTR cmd
)
624 TCHAR szMsg
[RC_STRING_MAX_SIZE
];
625 TCHAR cmdline
[CMDLINE_LENGTH
];
627 #ifdef FEATURE_REDIRECTION
628 TCHAR in
[CMDLINE_LENGTH
] = _T("");
629 TCHAR out
[CMDLINE_LENGTH
] = _T("");
630 TCHAR err
[CMDLINE_LENGTH
] = _T("");
631 TCHAR szTempPath
[MAX_PATH
] = _T(".\\");
632 TCHAR szFileName
[2][MAX_PATH
] = {_T(""), _T("")};
633 HANDLE hFile
[2] = {INVALID_HANDLE_VALUE
, INVALID_HANDLE_VALUE
};
639 BOOL bNewBatch
= TRUE
;
643 #endif /* FEATURE_REDIRECTION */
645 _tcscpy (cmdline
, cmd
);
649 DebugPrintf (_T("ParseCommandLine: (\'%s\')\n"), s
);
652 #ifdef FEATURE_ALIASES
653 /* expand all aliases */
654 ExpandAlias (s
, CMDLINE_LENGTH
);
655 #endif /* FEATURE_ALIAS */
657 #ifdef FEATURE_REDIRECTION
658 /* find the temp path to store temporary files */
659 Length
= GetTempPath (MAX_PATH
, szTempPath
);
660 if (Length
> 0 && Length
< MAX_PATH
)
662 Attributes
= GetFileAttributes(szTempPath
);
663 if (Attributes
== 0xffffffff ||
664 !(Attributes
& FILE_ATTRIBUTE_DIRECTORY
))
669 if (Length
== 0 || Length
>= MAX_PATH
)
671 _tcscpy(szTempPath
, _T(".\\"));
673 if (szTempPath
[_tcslen (szTempPath
) - 1] != _T('\\'))
674 _tcscat (szTempPath
, _T("\\"));
676 /* get the redirections from the command line */
677 num
= GetRedirection (s
, in
, out
, err
, &nRedirFlags
);
679 /* more efficient, but do we really need to do this? */
680 for (t
= in
; _istspace (*t
); t
++)
684 for (t
= out
; _istspace (*t
); t
++)
688 for (t
= err
; _istspace (*t
); t
++)
692 if(bc
&& !_tcslen (in
) && _tcslen (bc
->In
))
694 if(bc
&& !out
[0] && _tcslen(bc
->Out
))
696 nRedirFlags
|= OUTPUT_APPEND
;
697 _tcscpy(out
, bc
->Out
);
699 if(bc
&& !_tcslen (err
) && _tcslen (bc
->Err
))
701 nRedirFlags
|= ERROR_APPEND
;
702 _tcscpy(err
, bc
->Err
);
706 /* Set up the initial conditions ... */
707 /* preserve STDIN, STDOUT and STDERR handles */
708 hOldConIn
= GetStdHandle (STD_INPUT_HANDLE
);
709 hOldConOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
710 hOldConErr
= GetStdHandle (STD_ERROR_HANDLE
);
716 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
718 /* we need make sure the LastError msg is zero before calling CreateFile */
721 /* Set up pipe for the standard input handler */
722 hFile
= CreateFile (in
, GENERIC_READ
, FILE_SHARE_READ
, &sa
, OPEN_EXISTING
,
723 FILE_ATTRIBUTE_NORMAL
, NULL
);
724 if (hFile
== INVALID_HANDLE_VALUE
)
726 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR1
, szMsg
, RC_STRING_MAX_SIZE
);
727 ConErrPrintf(szMsg
, in
);
731 if (!SetStdHandle (STD_INPUT_HANDLE
, hFile
))
733 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR1
, szMsg
, RC_STRING_MAX_SIZE
);
734 ConErrPrintf(szMsg
, in
);
738 DebugPrintf (_T("Input redirected from: %s\n"), in
);
742 /* Now do all but the last pipe command */
743 *szFileName
[0] = _T('\0');
744 hFile
[0] = INVALID_HANDLE_VALUE
;
748 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
750 /* Create unique temporary file name */
751 GetTempFileName (szTempPath
, _T("CMD"), 0, szFileName
[1]);
753 /* we need make sure the LastError msg is zero before calling CreateFile */
756 /* Set current stdout to temporary file */
757 hFile
[1] = CreateFile (szFileName
[1], GENERIC_WRITE
, 0, &sa
,
758 TRUNCATE_EXISTING
, FILE_ATTRIBUTE_TEMPORARY
, NULL
);
760 if (hFile
[1] == INVALID_HANDLE_VALUE
)
762 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR2
, szMsg
, RC_STRING_MAX_SIZE
);
767 SetStdHandle (STD_OUTPUT_HANDLE
, hFile
[1]);
771 /* close stdout file */
772 SetStdHandle (STD_OUTPUT_HANDLE
, hOldConOut
);
773 if ((hFile
[1] != INVALID_HANDLE_VALUE
) && (hFile
[1] != hOldConOut
))
775 CloseHandle (hFile
[1]);
776 hFile
[1] = INVALID_HANDLE_VALUE
;
779 /* close old stdin file */
780 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
781 if ((hFile
[0] != INVALID_HANDLE_VALUE
) && (hFile
[0] != hOldConIn
))
783 /* delete old stdin file, if it is a real file */
784 CloseHandle (hFile
[0]);
785 hFile
[0] = INVALID_HANDLE_VALUE
;
786 DeleteFile (szFileName
[0]);
787 *szFileName
[0] = _T('\0');
790 /* copy stdout file name to stdin file name */
791 _tcscpy (szFileName
[0], szFileName
[1]);
792 *szFileName
[1] = _T('\0');
794 /* we need make sure the LastError msg is zero before calling CreateFile */
797 /* open new stdin file */
798 hFile
[0] = CreateFile (szFileName
[0], GENERIC_READ
, 0, &sa
,
799 OPEN_EXISTING
, FILE_ATTRIBUTE_TEMPORARY
, NULL
);
800 SetStdHandle (STD_INPUT_HANDLE
, hFile
[0]);
802 s
= s
+ _tcslen (s
) + 1;
805 /* Now set up the end conditions... */
806 /* redirect STDOUT */
809 /* Final output to here */
811 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
813 /* we need make sure the LastError msg is zero before calling CreateFile */
816 hFile
= CreateFile (out
, GENERIC_WRITE
, FILE_SHARE_WRITE
| FILE_SHARE_READ
| FILE_SHARE_DELETE
, &sa
,
817 (nRedirFlags
& OUTPUT_APPEND
) ? OPEN_ALWAYS
: CREATE_ALWAYS
,
818 FILE_ATTRIBUTE_NORMAL
| FILE_FLAG_WRITE_THROUGH
, NULL
);
820 if (hFile
== INVALID_HANDLE_VALUE
)
822 INT size
= _tcslen(out
)-1;
824 if (out
[size
] != _T(':'))
826 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR3
, szMsg
, RC_STRING_MAX_SIZE
);
827 ConErrPrintf(szMsg
, out
);
832 hFile
= CreateFile (out
, GENERIC_WRITE
, FILE_SHARE_WRITE
| FILE_SHARE_READ
| FILE_SHARE_DELETE
, &sa
,
833 (nRedirFlags
& OUTPUT_APPEND
) ? OPEN_ALWAYS
: CREATE_ALWAYS
,
834 FILE_ATTRIBUTE_NORMAL
| FILE_FLAG_WRITE_THROUGH
, NULL
);
836 if (hFile
== INVALID_HANDLE_VALUE
)
838 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR3
, szMsg
, RC_STRING_MAX_SIZE
);
839 ConErrPrintf(szMsg
, out
);
845 if (!SetStdHandle (STD_OUTPUT_HANDLE
, hFile
))
847 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR3
, szMsg
, RC_STRING_MAX_SIZE
);
848 ConErrPrintf(szMsg
, out
);
852 if (nRedirFlags
& OUTPUT_APPEND
)
856 if (GetFileType (hFile
) == FILE_TYPE_DISK
)
857 SetFilePointer (hFile
, 0, &lHighPos
, FILE_END
);
860 DebugPrintf (_T("Output redirected to: %s\n"), out
);
863 else if (hOldConOut
!= INVALID_HANDLE_VALUE
)
865 /* Restore original stdout */
866 HANDLE hOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
867 SetStdHandle (STD_OUTPUT_HANDLE
, hOldConOut
);
868 if (hOldConOut
!= hOut
)
870 hOldConOut
= INVALID_HANDLE_VALUE
;
873 /* redirect STDERR */
876 /* Final output to here */
878 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
880 if (!_tcscmp (err
, out
))
883 DebugPrintf (_T("Stdout and stderr will use the same file!!\n"));
885 DuplicateHandle (GetCurrentProcess (),
886 GetStdHandle (STD_OUTPUT_HANDLE
),
887 GetCurrentProcess (),
888 &hFile
, 0, TRUE
, DUPLICATE_SAME_ACCESS
);
892 hFile
= CreateFile (err
,
894 FILE_SHARE_WRITE
| FILE_SHARE_READ
| FILE_SHARE_DELETE
,
896 (nRedirFlags
& ERROR_APPEND
) ? OPEN_ALWAYS
: CREATE_ALWAYS
,
897 FILE_ATTRIBUTE_NORMAL
| FILE_FLAG_WRITE_THROUGH
,
899 if (hFile
== INVALID_HANDLE_VALUE
)
901 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR3
, szMsg
, RC_STRING_MAX_SIZE
);
902 ConErrPrintf(szMsg
, err
);
907 if (!SetStdHandle (STD_ERROR_HANDLE
, hFile
))
909 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR3
, szMsg
, RC_STRING_MAX_SIZE
);
910 ConErrPrintf(szMsg
, err
);
914 if (nRedirFlags
& ERROR_APPEND
)
918 if (GetFileType (hFile
) == FILE_TYPE_DISK
)
919 SetFilePointer (hFile
, 0, &lHighPos
, FILE_END
);
922 DebugPrintf (_T("Error redirected to: %s\n"), err
);
925 else if (hOldConErr
!= INVALID_HANDLE_VALUE
)
927 /* Restore original stderr */
928 HANDLE hErr
= GetStdHandle (STD_ERROR_HANDLE
);
929 SetStdHandle (STD_ERROR_HANDLE
, hOldConErr
);
930 if (hOldConErr
!= hErr
)
932 hOldConErr
= INVALID_HANDLE_VALUE
;
939 /* process final command */
942 #ifdef FEATURE_REDIRECTION
944 AddBatchRedirection(in
, out
, err
);
945 /* close old stdin file */
946 #if 0 /* buggy implementation */
947 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
948 if ((hFile
[0] != INVALID_HANDLE_VALUE
) &&
949 (hFile
[0] != hOldConIn
))
951 /* delete old stdin file, if it is a real file */
952 CloseHandle (hFile
[0]);
953 hFile
[0] = INVALID_HANDLE_VALUE
;
954 DeleteFile (szFileName
[0]);
955 *szFileName
[0] = _T('\0');
958 /* Restore original STDIN */
959 if (hOldConIn
!= INVALID_HANDLE_VALUE
)
961 HANDLE hIn
= GetStdHandle (STD_INPUT_HANDLE
);
962 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
963 if (hOldConIn
!= hIn
)
965 hOldConIn
= INVALID_HANDLE_VALUE
;
970 DebugPrintf (_T("Can't restore STDIN! Is invalid!!\n"), out
);
973 #endif /* buggy implementation */
976 if (hOldConIn
!= INVALID_HANDLE_VALUE
)
978 HANDLE hIn
= GetStdHandle (STD_INPUT_HANDLE
);
979 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
980 if (hIn
== INVALID_HANDLE_VALUE
)
983 DebugPrintf (_T("Previous STDIN is invalid!!\n"));
988 if (GetFileType (hIn
) == FILE_TYPE_DISK
)
992 CloseHandle (hFile
[0]);
993 hFile
[0] = INVALID_HANDLE_VALUE
;
994 DeleteFile (szFileName
[0]);
995 *szFileName
[0] = _T('\0');
1000 DebugPrintf (_T("hFile[0] and hIn dont match!!!\n"));
1008 /* Restore original STDOUT */
1009 if (hOldConOut
!= INVALID_HANDLE_VALUE
)
1011 HANDLE hOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
1012 SetStdHandle (STD_OUTPUT_HANDLE
, hOldConOut
);
1013 if (hOldConOut
!= hOut
)
1015 hOldConOut
= INVALID_HANDLE_VALUE
;
1018 /* Restore original STDERR */
1019 if (hOldConErr
!= INVALID_HANDLE_VALUE
)
1021 HANDLE hErr
= GetStdHandle (STD_ERROR_HANDLE
);
1022 SetStdHandle (STD_ERROR_HANDLE
, hOldConErr
);
1023 if (hOldConErr
!= hErr
)
1025 hOldConErr
= INVALID_HANDLE_VALUE
;
1027 #endif /* FEATURE_REDIRECTION */
1032 * do the prompt/input/process loop
1037 ProcessInput (BOOL bFlag
)
1039 TCHAR commandline
[CMDLINE_LENGTH
];
1040 TCHAR
*readline
= NULL
;
1046 readline
= malloc(CMDLINE_LENGTH
* sizeof(TCHAR
));
1050 /* if no batch input then... */
1051 if (!(ip
= ReadBatchLine (&bEchoThisLine
)))
1056 readline
= ReadCommand (readline
, CMDLINE_LENGTH
);
1058 bEchoThisLine
= FALSE
;
1082 if ((tp
= FindArg (*ip
- _T('0'))))
1084 cp
= _stpcpy (cp
, tp
);
1092 cp
+= _stprintf (cp
, _T("%u"), nErrorLevel
);
1097 tp
= _tcschr(ip
, _T('%'));
1099 (tp
<= _tcschr(ip
, _T(' ')) - 1))
1105 /* FIXME: Correct error handling when it can not alloc memmory */
1108 if (_tcsicmp(ip
,_T("cd")) ==0)
1110 TCHAR szPath
[MAX_PATH
];
1111 GetCurrentDirectory (MAX_PATH
, szPath
);
1112 cp
= _stpcpy (cp
, szPath
);
1115 else if (_tcsicmp(ip
,_T("time")) ==0)
1121 _sntprintf(szTime
,40,_T("%02d%c%02d%c%02d%c%02d"), t
.wHour
, cTimeSeparator
,t
.wMinute
, cTimeSeparator
,t
.wSecond
, cDecimalSeparator
, t
.wMilliseconds
);
1122 cp
= _stpcpy (cp
, szTime
);
1126 else if (_tcsicmp(ip
,_T("date")) ==0)
1130 GetDateFormat(LOCALE_USER_DEFAULT
, 0, NULL
, _T("ddd"), szDate
, sizeof (szDate
));
1131 cp
= _stpcpy (cp
, szDate
);
1132 cp
= _stpcpy (cp
, _T(" "));
1133 GetDateFormat(LOCALE_USER_DEFAULT
, DATE_SHORTDATE
, NULL
, NULL
, szDate
, sizeof (szDate
));
1134 cp
= _stpcpy (cp
, szDate
);
1138 else if (_tcsicmp(ip
,_T("random")) ==0)
1141 /* Get random number */
1142 _itot(rand(),szRand
,10);
1143 cp
= _stpcpy (cp
, szRand
);
1147 else if (_tcsicmp(ip
,_T("cmdcmdline")) ==0)
1150 /* Get random number */
1151 pargv
= GetCommandLine();
1152 cp
= _stpcpy (cp
, pargv
);
1155 /* %CMDEXTVERSION% */
1156 else if (_tcsicmp(ip
,_T("cmdextversion")) ==0)
1159 /* Set version number to 2 */
1161 cp
= _stpcpy (cp
, szVER
);
1165 else if (_tcsicmp(ip
,_T("errorlevel")) ==0)
1167 evar
= malloc ( size
* sizeof(TCHAR
));
1171 memset(evar
,0,512 * sizeof(TCHAR
));
1172 _itot(nErrorLevel
,evar
,10);
1173 cp
= _stpcpy (cp
, evar
);
1179 evar
= malloc ( 512 * sizeof(TCHAR
));
1183 size
= GetEnvironmentVariable (ip
, evar
, 512);
1184 if(GetLastError() == ERROR_ENVVAR_NOT_FOUND
)
1186 /* if no env var is found you must
1187 continue with what was input*/
1188 cp
= _stpcpy (cp
, _T("%"));
1189 cp
= _stpcpy (cp
, ip
);
1190 cp
= _stpcpy (cp
, _T("%"));
1196 evar
= realloc(evar
,size
* sizeof(TCHAR
) );
1201 size
= GetEnvironmentVariable (ip
, evar
, size
);
1206 cp
= _stpcpy (cp
, evar
);
1229 if (_istcntrl (*ip
))
1236 /* strip trailing spaces */
1237 while ((--cp
>= commandline
) && _istspace (*cp
));
1239 *(cp
+ 1) = _T('\0');
1242 /* Echo batch file line */
1246 ConOutPuts (commandline
);
1251 ParseCommandLine (commandline
);
1252 if (bEcho
&& !bIgnoreEcho
)
1254 bIgnoreEcho
= FALSE
;
1257 while (!bCanExit
|| !bExit
);
1264 * control-break handler.
1266 BOOL WINAPI
BreakHandler (DWORD dwCtrlType
)
1269 if ((dwCtrlType
!= CTRL_C_EVENT
) &&
1270 (dwCtrlType
!= CTRL_BREAK_EVENT
))
1273 if (bChildProcessRunning
== TRUE
)
1275 GenerateConsoleCtrlEvent (CTRL_C_EVENT
,
1280 /* FIXME: Handle batch files */
1282 /* FIXME: Print "^C" */
1289 VOID
AddBreakHandler (VOID
)
1291 SetConsoleCtrlHandler ((PHANDLER_ROUTINE
)BreakHandler
, TRUE
);
1295 VOID
RemoveBreakHandler (VOID
)
1297 SetConsoleCtrlHandler ((PHANDLER_ROUTINE
)BreakHandler
, FALSE
);
1302 * show commands and options that are available.
1309 /* print command list */
1310 ConOutResPuts(STRING_CMD_HELP1
);
1313 /* print feature list */
1314 ConOutResPuts(STRING_CMD_HELP2
);
1316 #ifdef FEATURE_ALIASES
1317 ConOutResPuts(STRING_CMD_HELP3
);
1319 #ifdef FEATURE_HISTORY
1320 ConOutResPuts(STRING_CMD_HELP4
);
1322 #ifdef FEATURE_UNIX_FILENAME_COMPLETION
1323 ConOutResPuts(STRING_CMD_HELP5
);
1325 #ifdef FEATURE_DIRECTORY_STACK
1326 ConOutResPuts(STRING_CMD_HELP6
);
1328 #ifdef FEATURE_REDIRECTION
1329 ConOutResPuts(STRING_CMD_HELP7
);
1331 ConOutChar(_T('\n'));
1336 * set up global initializations and process parameters
1338 * argc - number of parameters to command.com
1339 * argv - command-line parameters
1343 Initialize (int argc
, TCHAR
* argv
[])
1345 TCHAR commandline
[CMDLINE_LENGTH
];
1346 TCHAR ModuleName
[_MAX_PATH
+ 1];
1351 //TCHAR *ptr, *cmdLine;
1353 /* get version information */
1354 osvi
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
1355 GetVersionEx (&osvi
);
1357 /* Some people like to run ReactOS cmd.exe on Win98, it helps in the
1358 build process. So don't link implicitly against ntdll.dll, load it
1359 dynamically instead */
1361 if (osvi
.dwPlatformId
== VER_PLATFORM_WIN32_NT
)
1363 /* ntdll is always present on NT */
1364 NtDllModule
= GetModuleHandle(TEXT("ntdll.dll"));
1368 /* not all 9x versions have a ntdll.dll, try to load it */
1369 NtDllModule
= LoadLibrary(TEXT("ntdll.dll"));
1372 if (NtDllModule
!= NULL
)
1374 NtQueryInformationProcessPtr
= (NtQueryInformationProcessProc
)GetProcAddress(NtDllModule
, "NtQueryInformationProcess");
1375 NtReadVirtualMemoryPtr
= (NtReadVirtualMemoryProc
)GetProcAddress(NtDllModule
, "NtReadVirtualMemory");
1382 DebugPrintf (_T("[command args:\n"));
1383 for (x
= 0; x
< argc
; x
++)
1385 DebugPrintf (_T("%d. %s\n"), x
, argv
[x
]);
1387 DebugPrintf (_T("]\n"));
1392 /* get default input and output console handles */
1393 hOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
1394 hIn
= GetStdHandle (STD_INPUT_HANDLE
);
1396 /* Set EnvironmentVariable PROMPT if it does not exists any env value.
1397 for you can change the EnvirommentVariable for prompt before cmd start
1398 this patch are not 100% right, if it does not exists a PROMPT value cmd should use
1399 $P$G as defualt not set EnvirommentVariable PROMPT to $P$G if it does not exists */
1400 if (GetEnvironmentVariable(_T("PROMPT"),lpBuffer
, 2 * sizeof(TCHAR
)) == 0)
1401 SetEnvironmentVariable (_T("PROMPT"), _T("$P$G"));
1404 if (argc
>= 2 && !_tcsncmp (argv
[1], _T("/?"), 2))
1406 ConOutResPaging(TRUE
,STRING_CMD_HELP8
);
1409 SetConsoleMode (hIn
, ENABLE_PROCESSED_INPUT
);
1411 #ifdef INCLUDE_CMD_CHDIR
1415 #ifdef FATURE_ALIASES
1421 for (i
= 1; i
< argc
; i
++)
1423 if (!_tcsicmp (argv
[i
], _T("/p")))
1425 if (!IsExistingFile (_T("\\autoexec.bat")))
1427 #ifdef INCLUDE_CMD_DATE
1428 cmd_date (_T(""), _T(""));
1430 #ifdef INCLUDE_CMD_TIME
1431 cmd_time (_T(""), _T(""));
1436 ParseCommandLine (_T("\\autoexec.bat"));
1440 else if (!_tcsicmp (argv
[i
], _T("/c")))
1442 /* This just runs a program and exits */
1446 _tcscpy (commandline
, argv
[i
]);
1449 _tcscat (commandline
, _T(" "));
1450 _tcscat (commandline
, argv
[i
]);
1453 ParseCommandLine(commandline
);
1454 ExitProcess (ProcessInput (TRUE
));
1461 else if (!_tcsicmp (argv
[i
], _T("/k")))
1463 /* This just runs a program and remains */
1467 _tcscpy (commandline
, argv
[i
]);
1470 _tcscat (commandline
, _T(" "));
1471 _tcscat (commandline
, argv
[i
]);
1474 ParseCommandLine(commandline
);
1477 #ifdef INCLUDE_CMD_COLOR
1478 else if (!_tcsnicmp (argv
[i
], _T("/t:"), 3))
1480 /* process /t (color) argument */
1481 wDefColor
= (WORD
)_tcstoul (&argv
[i
][3], NULL
, 16);
1483 SetScreenColor (wColor
, TRUE
);
1489 /* run cmdstart.bat */
1490 if (IsExistingFile (_T("cmdstart.bat")))
1492 ParseCommandLine (_T("cmdstart.bat"));
1494 else if (IsExistingFile (_T("\\cmdstart.bat")))
1496 ParseCommandLine (_T("\\cmdstart.bat"));
1501 /* try to run cmdstart.bat from install dir */
1504 _tcscpy (commandline
, argv
[0]);
1505 p
= _tcsrchr (commandline
, _T('\\')) + 1;
1506 _tcscpy (p
, _T("cmdstart.bat"));
1508 if (IsExistingFile (_T("commandline")))
1510 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR4
, szMsg
, RC_STRING_MAX_SIZE
);
1511 ConErrPrintf(szMsg
, commandline
);
1512 ParseCommandLine (commandline
);
1517 #ifdef FEATURE_DIR_STACK
1518 /* initialize directory stack */
1519 InitDirectoryStack ();
1523 #ifdef FEATURE_HISTORY
1524 /*initialize history*/
1528 /* Set COMSPEC environment variable */
1529 if (0 != GetModuleFileName (NULL
, ModuleName
, _MAX_PATH
+ 1))
1531 ModuleName
[_MAX_PATH
] = _T('\0');
1532 SetEnvironmentVariable (_T("COMSPEC"), ModuleName
);
1535 /* add ctrl break handler */
1540 static VOID
Cleanup (int argc
, TCHAR
*argv
[])
1543 TCHAR szMsg
[RC_STRING_MAX_SIZE
];
1546 /* run cmdexit.bat */
1547 if (IsExistingFile (_T("cmdexit.bat")))
1549 ConErrResPuts(STRING_CMD_ERROR5
);
1551 ParseCommandLine (_T("cmdexit.bat"));
1553 else if (IsExistingFile (_T("\\cmdexit.bat")))
1555 ConErrResPuts (STRING_CMD_ERROR5
);
1556 ParseCommandLine (_T("\\cmdexit.bat"));
1561 /* try to run cmdexit.bat from install dir */
1562 TCHAR commandline
[CMDLINE_LENGTH
];
1565 _tcscpy (commandline
, argv
[0]);
1566 p
= _tcsrchr (commandline
, _T('\\')) + 1;
1567 _tcscpy (p
, _T("cmdexit.bat"));
1569 if (IsExistingFile (_T("commandline")))
1571 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR4
, szMsg
, RC_STRING_MAX_SIZE
);
1572 ConErrPrintf(szMsg
, commandline
);
1573 ParseCommandLine (commandline
);
1578 #ifdef FEATURE_ALIASES
1582 #ifdef FEATURE_DIECTORY_STACK
1583 /* destroy directory stack */
1584 DestroyDirectoryStack ();
1587 #ifdef INCLUDE_CMD_CHDIR
1591 #ifdef FEATURE_HISTORY
1596 /* remove ctrl break handler */
1597 RemoveBreakHandler ();
1598 SetConsoleMode( GetStdHandle( STD_INPUT_HANDLE
),
1599 ENABLE_LINE_INPUT
| ENABLE_PROCESSED_INPUT
| ENABLE_ECHO_INPUT
);
1601 if (NtDllModule
!= NULL
)
1603 FreeLibrary(NtDllModule
);
1609 PWCHAR
* _CommandLineToArgvW(PWCHAR lpCmdLine
, int *pNumArgs
)
1611 PWCHAR
* argvw
= NULL
;
1612 PWCHAR ptr
= lpCmdLine
;
1619 while(lpCmdLine
&& *lpCmdLine
)
1621 while (iswspace(*lpCmdLine
)) lpCmdLine
++;
1624 if ((NumArgs
% 10)==0)
1626 PWCHAR
* old_argvw
= argvw
;
1627 argvw
= malloc((NumArgs
+ 10) * sizeof(PWCHAR
));
1628 memcpy(argvw
, old_argvw
, NumArgs
* sizeof(PWCHAR
));
1631 ptr
= wcschr(lpCmdLine
, L
' ');
1634 len
= ptr
- lpCmdLine
;
1638 len
= wcslen(lpCmdLine
);
1640 str
= malloc((len
+ 1) * sizeof(WCHAR
));
1641 memcpy(str
, lpCmdLine
, len
* sizeof(WCHAR
));
1648 *pNumArgs
= NumArgs
;
1660 int _main (int argc
, char *argv
[])
1663 TCHAR startPath
[MAX_PATH
];
1664 CONSOLE_SCREEN_BUFFER_INFO Info
;
1670 argv
= _CommandLineToArgvW(GetCommandLineW(), &argc
);
1672 argv
= CommandLineToArgvW(GetCommandLineW(), &argc
);
1676 GetCurrentDirectory(MAX_PATH
,startPath
);
1683 hConsole
= CreateFile(_T("CONOUT$"), GENERIC_READ
|GENERIC_WRITE
,
1684 FILE_SHARE_READ
|FILE_SHARE_WRITE
, NULL
,
1685 OPEN_EXISTING
, 0, NULL
);
1686 if (GetConsoleScreenBufferInfo(hConsole
, &Info
) == FALSE
)
1688 ConErrFormatMessage(GetLastError());
1691 wColor
= Info
.wAttributes
;
1694 InputCodePage
= GetConsoleCP();
1695 OutputCodePage
= GetConsoleOutputCP();
1696 CMD_ModuleHandle
= GetModuleHandle(NULL
);
1698 /* check switches on command-line */
1699 Initialize(argc
, argv
);
1701 /* call prompt routine */
1702 nExitCode
= ProcessInput(FALSE
);
1705 /* do the cleanup */
1706 Cleanup(argc
, argv
);