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
];
302 TCHAR szWindowTitle
[MAX_PATH
];
303 DWORD dwExitCode
= 0;
306 DebugPrintf (_T("Execute: \'%s\' \'%s\'\n"), first
, rest
);
309 /* we need biger buffer that First, Rest, Full are already
310 need rewrite some code to use realloc when it need instead
311 of add 512bytes extra */
313 first
= malloc ( _tcslen(First
) + 512 * sizeof(TCHAR
));
316 error_out_of_memory();
320 rest
= malloc ( _tcslen(Rest
) + 512 * sizeof(TCHAR
));
324 error_out_of_memory();
328 full
= malloc ( _tcslen(Full
) + 512 * sizeof(TCHAR
));
333 error_out_of_memory();
338 /* Though it was already parsed once, we have a different set of rules
339 for parsing before we pass to CreateProccess */
340 if(!_tcschr(Full
,_T('\"')))
342 _tcscpy(first
,First
);
349 BOOL bInside
= FALSE
;
354 /* find the end of the command and start of the args */
355 for(i
= 0; i
< _tcslen(first
); i
++)
357 if(!_tcsncmp(&first
[i
], _T("\""), 1))
359 if(!_tcsncmp(&first
[i
], _T(" "), 1) && !bInside
)
361 _tcscpy(rest
,&first
[i
]);
368 /* remove any slashes */
369 while(i
< _tcslen(first
))
371 if(first
[i
] == _T('\"'))
372 memmove(&first
[i
],&first
[i
+ 1], _tcslen(&first
[i
]) * sizeof(TCHAR
));
376 /* Drop quotes around it just in case there is a space */
377 _tcscpy(full
,_T("\""));
379 _tcscat(full
,_T("\" "));
383 /* check for a drive change */
384 if ((_istalpha (first
[0])) && (!_tcscmp (first
+ 1, _T(":"))))
387 if (!SetCurrentDirectory(first
))
388 /* Guess they changed disc or something, handle that gracefully and get to root */
395 working
= SetCurrentDirectory(str
);
398 if (!working
) ConErrResPuts (STRING_FREE_ERROR1
);
403 /* get the PATH environment variable and parse it */
404 /* search the PATH environment variable for the binary */
405 if (!SearchForExecutable (first
, szFullName
))
407 error_bad_command ();
411 GetConsoleTitle (szWindowTitle
, MAX_PATH
);
413 /* check if this is a .BAT or .CMD file */
414 if (!_tcsicmp (_tcsrchr (szFullName
, _T('.')), _T(".bat")) ||
415 !_tcsicmp (_tcsrchr (szFullName
, _T('.')), _T(".cmd")))
418 DebugPrintf (_T("[BATCH: %s %s]\n"), szFullName
, rest
);
420 Batch (szFullName
, first
, rest
);
424 /* exec the program */
425 PROCESS_INFORMATION prci
;
429 DebugPrintf (_T("[EXEC: %s %s]\n"), full
, rest
);
431 /* build command line for CreateProcess() */
433 /* fill startup info */
434 memset (&stui
, 0, sizeof (STARTUPINFO
));
435 stui
.cb
= sizeof (STARTUPINFO
);
436 stui
.dwFlags
= STARTF_USESHOWWINDOW
;
437 stui
.wShowWindow
= SW_SHOWDEFAULT
;
439 // return console to standard mode
440 SetConsoleMode (GetStdHandle(STD_INPUT_HANDLE
),
441 ENABLE_LINE_INPUT
| ENABLE_PROCESSED_INPUT
| ENABLE_ECHO_INPUT
);
443 if (CreateProcess (szFullName
,
448 CREATE_NEW_PROCESS_GROUP
,
454 if (IsConsoleProcess(prci
.hProcess
))
456 /* FIXME: Protect this with critical section */
457 bChildProcessRunning
= TRUE
;
458 dwChildProcessId
= prci
.dwProcessId
;
460 WaitForSingleObject (prci
.hProcess
, INFINITE
);
462 /* FIXME: Protect this with critical section */
463 bChildProcessRunning
= FALSE
;
465 GetExitCodeProcess (prci
.hProcess
, &dwExitCode
);
466 nErrorLevel
= (INT
)dwExitCode
;
468 CloseHandle (prci
.hThread
);
469 CloseHandle (prci
.hProcess
);
474 DebugPrintf (_T("[ShellExecute: %s]\n"), full
);
476 // See if we can run this with ShellExecute() ie myfile.xls
480 DebugPrintf (_T("[ShellExecute failed!: %s]\n"), full
);
482 error_bad_command ();
485 // restore console mode
486 SetConsoleMode( GetStdHandle( STD_INPUT_HANDLE
),
487 ENABLE_PROCESSED_INPUT
);
490 /* Get code page if it has been change */
491 InputCodePage
= GetConsoleCP();
492 OutputCodePage
= GetConsoleOutputCP();
493 SetConsoleTitle (szWindowTitle
);
502 * look through the internal commands and determine whether or not this
503 * command is one of them. If it is, call the command. If not, call
504 * execute to run it as an external program.
506 * line - the command line of the program to run
511 DoCommand (LPTSTR line
)
513 TCHAR com
[CMDLINE_LENGTH
]; /* the first word in the command */
516 LPTSTR rest
; /* pointer to the rest of the command line */
521 DebugPrintf (_T("DoCommand: (\'%s\')\n"), line
);
524 /* Skip over initial white space */
525 while (_istspace (*line
))
531 /* Anything to do ? */
534 if (*rest
== _T('"'))
536 /* treat quoted words specially */
540 while(*rest
!= _T('\0') && *rest
!= _T('"'))
541 *cp
++ = _totlower (*rest
++);
542 if (*rest
== _T('"'))
547 while (!IsDelimiter (*rest
))
548 *cp
++ = _totlower (*rest
++);
552 /* Terminate first word */
555 /* commands are limited to MAX_PATH */
556 if(_tcslen(com
) > MAX_PATH
)
562 /* Skip over whitespace to rest of line */
563 while (_istspace (*rest
))
566 /* Scan internal command table */
567 for (cmdptr
= cmds
;; cmdptr
++)
569 /* If end of table execute ext cmd */
570 if (cmdptr
->name
== NULL
)
572 Execute (line
, com
, rest
);
576 if (!_tcscmp (com
, cmdptr
->name
))
578 cmdptr
->func (com
, rest
);
582 /* The following code handles the case of commands like CD which
583 * are recognised even when the command name and parameter are
584 * not space separated.
590 /* Get length of command name */
591 cl
= _tcslen (cmdptr
->name
);
593 if ((cmdptr
->flags
& CMD_SPECIAL
) &&
594 (!_tcsncmp (cmdptr
->name
, com
, cl
)) &&
595 (_tcschr (_T("\\.-"), *(com
+ cl
))))
597 /* OK its one of the specials...*/
599 /* Terminate first word properly */
602 /* Call with new rest */
603 cmdptr
->func (com
, cstart
+ cl
);
612 * process the command line and execute the appropriate functions
613 * full input/output redirection and piping are supported
616 VOID
ParseCommandLine (LPTSTR cmd
)
618 TCHAR szMsg
[RC_STRING_MAX_SIZE
];
619 TCHAR cmdline
[CMDLINE_LENGTH
];
621 #ifdef FEATURE_REDIRECTION
622 TCHAR in
[CMDLINE_LENGTH
] = _T("");
623 TCHAR out
[CMDLINE_LENGTH
] = _T("");
624 TCHAR err
[CMDLINE_LENGTH
] = _T("");
625 TCHAR szTempPath
[MAX_PATH
] = _T(".\\");
626 TCHAR szFileName
[2][MAX_PATH
] = {_T(""), _T("")};
627 HANDLE hFile
[2] = {INVALID_HANDLE_VALUE
, INVALID_HANDLE_VALUE
};
633 BOOL bNewBatch
= TRUE
;
637 #endif /* FEATURE_REDIRECTION */
639 _tcscpy (cmdline
, cmd
);
643 DebugPrintf (_T("ParseCommandLine: (\'%s\')\n"), s
);
646 #ifdef FEATURE_ALIASES
647 /* expand all aliases */
648 ExpandAlias (s
, CMDLINE_LENGTH
);
649 #endif /* FEATURE_ALIAS */
651 #ifdef FEATURE_REDIRECTION
652 /* find the temp path to store temporary files */
653 Length
= GetTempPath (MAX_PATH
, szTempPath
);
654 if (Length
> 0 && Length
< MAX_PATH
)
656 Attributes
= GetFileAttributes(szTempPath
);
657 if (Attributes
== 0xffffffff ||
658 !(Attributes
& FILE_ATTRIBUTE_DIRECTORY
))
663 if (Length
== 0 || Length
>= MAX_PATH
)
665 _tcscpy(szTempPath
, _T(".\\"));
667 if (szTempPath
[_tcslen (szTempPath
) - 1] != _T('\\'))
668 _tcscat (szTempPath
, _T("\\"));
670 /* get the redirections from the command line */
671 num
= GetRedirection (s
, in
, out
, err
, &nRedirFlags
);
673 /* more efficient, but do we really need to do this? */
674 for (t
= in
; _istspace (*t
); t
++)
678 for (t
= out
; _istspace (*t
); t
++)
682 for (t
= err
; _istspace (*t
); t
++)
686 if(bc
&& !_tcslen (in
) && _tcslen (bc
->In
))
688 if(bc
&& !out
[0] && _tcslen(bc
->Out
))
690 nRedirFlags
|= OUTPUT_APPEND
;
691 _tcscpy(out
, bc
->Out
);
693 if(bc
&& !_tcslen (err
) && _tcslen (bc
->Err
))
695 nRedirFlags
|= ERROR_APPEND
;
696 _tcscpy(err
, bc
->Err
);
700 /* Set up the initial conditions ... */
701 /* preserve STDIN, STDOUT and STDERR handles */
702 hOldConIn
= GetStdHandle (STD_INPUT_HANDLE
);
703 hOldConOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
704 hOldConErr
= GetStdHandle (STD_ERROR_HANDLE
);
710 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
712 /* we need make sure the LastError msg is zero before calling CreateFile */
715 /* Set up pipe for the standard input handler */
716 hFile
= CreateFile (in
, GENERIC_READ
, FILE_SHARE_READ
, &sa
, OPEN_EXISTING
,
717 FILE_ATTRIBUTE_NORMAL
, NULL
);
718 if (hFile
== INVALID_HANDLE_VALUE
)
720 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR1
, szMsg
, RC_STRING_MAX_SIZE
);
721 ConErrPrintf(szMsg
, in
);
725 if (!SetStdHandle (STD_INPUT_HANDLE
, hFile
))
727 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR1
, szMsg
, RC_STRING_MAX_SIZE
);
728 ConErrPrintf(szMsg
, in
);
732 DebugPrintf (_T("Input redirected from: %s\n"), in
);
736 /* Now do all but the last pipe command */
737 *szFileName
[0] = _T('\0');
738 hFile
[0] = INVALID_HANDLE_VALUE
;
742 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
744 /* Create unique temporary file name */
745 GetTempFileName (szTempPath
, _T("CMD"), 0, szFileName
[1]);
747 /* we need make sure the LastError msg is zero before calling CreateFile */
750 /* Set current stdout to temporary file */
751 hFile
[1] = CreateFile (szFileName
[1], GENERIC_WRITE
, 0, &sa
,
752 TRUNCATE_EXISTING
, FILE_ATTRIBUTE_TEMPORARY
, NULL
);
754 if (hFile
[1] == INVALID_HANDLE_VALUE
)
756 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR2
, szMsg
, RC_STRING_MAX_SIZE
);
761 SetStdHandle (STD_OUTPUT_HANDLE
, hFile
[1]);
765 /* close stdout file */
766 SetStdHandle (STD_OUTPUT_HANDLE
, hOldConOut
);
767 if ((hFile
[1] != INVALID_HANDLE_VALUE
) && (hFile
[1] != hOldConOut
))
769 CloseHandle (hFile
[1]);
770 hFile
[1] = INVALID_HANDLE_VALUE
;
773 /* close old stdin file */
774 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
775 if ((hFile
[0] != INVALID_HANDLE_VALUE
) && (hFile
[0] != hOldConIn
))
777 /* delete old stdin file, if it is a real file */
778 CloseHandle (hFile
[0]);
779 hFile
[0] = INVALID_HANDLE_VALUE
;
780 DeleteFile (szFileName
[0]);
781 *szFileName
[0] = _T('\0');
784 /* copy stdout file name to stdin file name */
785 _tcscpy (szFileName
[0], szFileName
[1]);
786 *szFileName
[1] = _T('\0');
788 /* we need make sure the LastError msg is zero before calling CreateFile */
791 /* open new stdin file */
792 hFile
[0] = CreateFile (szFileName
[0], GENERIC_READ
, 0, &sa
,
793 OPEN_EXISTING
, FILE_ATTRIBUTE_TEMPORARY
, NULL
);
794 SetStdHandle (STD_INPUT_HANDLE
, hFile
[0]);
796 s
= s
+ _tcslen (s
) + 1;
799 /* Now set up the end conditions... */
800 /* redirect STDOUT */
803 /* Final output to here */
805 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
807 /* we need make sure the LastError msg is zero before calling CreateFile */
810 hFile
= CreateFile (out
, GENERIC_WRITE
, FILE_SHARE_WRITE
| FILE_SHARE_READ
| FILE_SHARE_DELETE
, &sa
,
811 (nRedirFlags
& OUTPUT_APPEND
) ? OPEN_ALWAYS
: CREATE_ALWAYS
,
812 FILE_ATTRIBUTE_NORMAL
| FILE_FLAG_WRITE_THROUGH
, NULL
);
814 if (hFile
== INVALID_HANDLE_VALUE
)
816 INT size
= _tcslen(out
)-1;
818 if (out
[size
] != _T(':'))
820 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR3
, szMsg
, RC_STRING_MAX_SIZE
);
821 ConErrPrintf(szMsg
, out
);
826 hFile
= CreateFile (out
, GENERIC_WRITE
, FILE_SHARE_WRITE
| FILE_SHARE_READ
| FILE_SHARE_DELETE
, &sa
,
827 (nRedirFlags
& OUTPUT_APPEND
) ? OPEN_ALWAYS
: CREATE_ALWAYS
,
828 FILE_ATTRIBUTE_NORMAL
| FILE_FLAG_WRITE_THROUGH
, NULL
);
830 if (hFile
== INVALID_HANDLE_VALUE
)
832 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR3
, szMsg
, RC_STRING_MAX_SIZE
);
833 ConErrPrintf(szMsg
, out
);
839 if (!SetStdHandle (STD_OUTPUT_HANDLE
, hFile
))
841 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR3
, szMsg
, RC_STRING_MAX_SIZE
);
842 ConErrPrintf(szMsg
, out
);
846 if (nRedirFlags
& OUTPUT_APPEND
)
850 if (GetFileType (hFile
) == FILE_TYPE_DISK
)
851 SetFilePointer (hFile
, 0, &lHighPos
, FILE_END
);
854 DebugPrintf (_T("Output redirected to: %s\n"), out
);
857 else if (hOldConOut
!= INVALID_HANDLE_VALUE
)
859 /* Restore original stdout */
860 HANDLE hOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
861 SetStdHandle (STD_OUTPUT_HANDLE
, hOldConOut
);
862 if (hOldConOut
!= hOut
)
864 hOldConOut
= INVALID_HANDLE_VALUE
;
867 /* redirect STDERR */
870 /* Final output to here */
872 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
874 if (!_tcscmp (err
, out
))
877 DebugPrintf (_T("Stdout and stderr will use the same file!!\n"));
879 DuplicateHandle (GetCurrentProcess (),
880 GetStdHandle (STD_OUTPUT_HANDLE
),
881 GetCurrentProcess (),
882 &hFile
, 0, TRUE
, DUPLICATE_SAME_ACCESS
);
886 hFile
= CreateFile (err
,
888 FILE_SHARE_WRITE
| FILE_SHARE_READ
| FILE_SHARE_DELETE
,
890 (nRedirFlags
& ERROR_APPEND
) ? OPEN_ALWAYS
: CREATE_ALWAYS
,
891 FILE_ATTRIBUTE_NORMAL
| FILE_FLAG_WRITE_THROUGH
,
893 if (hFile
== INVALID_HANDLE_VALUE
)
895 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR3
, szMsg
, RC_STRING_MAX_SIZE
);
896 ConErrPrintf(szMsg
, err
);
901 if (!SetStdHandle (STD_ERROR_HANDLE
, hFile
))
903 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR3
, szMsg
, RC_STRING_MAX_SIZE
);
904 ConErrPrintf(szMsg
, err
);
908 if (nRedirFlags
& ERROR_APPEND
)
912 if (GetFileType (hFile
) == FILE_TYPE_DISK
)
913 SetFilePointer (hFile
, 0, &lHighPos
, FILE_END
);
916 DebugPrintf (_T("Error redirected to: %s\n"), err
);
919 else if (hOldConErr
!= INVALID_HANDLE_VALUE
)
921 /* Restore original stderr */
922 HANDLE hErr
= GetStdHandle (STD_ERROR_HANDLE
);
923 SetStdHandle (STD_ERROR_HANDLE
, hOldConErr
);
924 if (hOldConErr
!= hErr
)
926 hOldConErr
= INVALID_HANDLE_VALUE
;
933 /* process final command */
936 #ifdef FEATURE_REDIRECTION
938 AddBatchRedirection(in
, out
, err
);
939 /* close old stdin file */
940 #if 0 /* buggy implementation */
941 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
942 if ((hFile
[0] != INVALID_HANDLE_VALUE
) &&
943 (hFile
[0] != hOldConIn
))
945 /* delete old stdin file, if it is a real file */
946 CloseHandle (hFile
[0]);
947 hFile
[0] = INVALID_HANDLE_VALUE
;
948 DeleteFile (szFileName
[0]);
949 *szFileName
[0] = _T('\0');
952 /* Restore original STDIN */
953 if (hOldConIn
!= INVALID_HANDLE_VALUE
)
955 HANDLE hIn
= GetStdHandle (STD_INPUT_HANDLE
);
956 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
957 if (hOldConIn
!= hIn
)
959 hOldConIn
= INVALID_HANDLE_VALUE
;
964 DebugPrintf (_T("Can't restore STDIN! Is invalid!!\n"), out
);
967 #endif /* buggy implementation */
970 if (hOldConIn
!= INVALID_HANDLE_VALUE
)
972 HANDLE hIn
= GetStdHandle (STD_INPUT_HANDLE
);
973 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
974 if (hIn
== INVALID_HANDLE_VALUE
)
977 DebugPrintf (_T("Previous STDIN is invalid!!\n"));
982 if (GetFileType (hIn
) == FILE_TYPE_DISK
)
986 CloseHandle (hFile
[0]);
987 hFile
[0] = INVALID_HANDLE_VALUE
;
988 DeleteFile (szFileName
[0]);
989 *szFileName
[0] = _T('\0');
994 DebugPrintf (_T("hFile[0] and hIn dont match!!!\n"));
1002 /* Restore original STDOUT */
1003 if (hOldConOut
!= INVALID_HANDLE_VALUE
)
1005 HANDLE hOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
1006 SetStdHandle (STD_OUTPUT_HANDLE
, hOldConOut
);
1007 if (hOldConOut
!= hOut
)
1009 hOldConOut
= INVALID_HANDLE_VALUE
;
1012 /* Restore original STDERR */
1013 if (hOldConErr
!= INVALID_HANDLE_VALUE
)
1015 HANDLE hErr
= GetStdHandle (STD_ERROR_HANDLE
);
1016 SetStdHandle (STD_ERROR_HANDLE
, hOldConErr
);
1017 if (hOldConErr
!= hErr
)
1019 hOldConErr
= INVALID_HANDLE_VALUE
;
1021 #endif /* FEATURE_REDIRECTION */
1026 * do the prompt/input/process loop
1031 ProcessInput (BOOL bFlag
)
1033 TCHAR commandline
[CMDLINE_LENGTH
];
1034 TCHAR readline
[CMDLINE_LENGTH
];
1043 /* if no batch input then... */
1044 if (!(ip
= ReadBatchLine (&bEchoThisLine
)))
1049 ReadCommand (readline
, CMDLINE_LENGTH
);
1051 bEchoThisLine
= FALSE
;
1075 if ((tp
= FindArg (*ip
- _T('0'))))
1077 cp
= _stpcpy (cp
, tp
);
1085 cp
+= _stprintf (cp
, _T("%u"), nErrorLevel
);
1090 tp
= _tcschr(ip
, _T('%'));
1092 (tp
<= _tcschr(ip
, _T(' ')) - 1))
1098 /* FIXME: Correct error handling when it can not alloc memmory */
1101 if (_tcsicmp(ip
,_T("cd")) ==0)
1103 TCHAR szPath
[MAX_PATH
];
1104 GetCurrentDirectory (MAX_PATH
, szPath
);
1105 cp
= _stpcpy (cp
, szPath
);
1108 else if (_tcsicmp(ip
,_T("time")) ==0)
1114 _sntprintf(szTime
,40,_T("%02d%c%02d%c%02d%c%02d"), t
.wHour
, cTimeSeparator
,t
.wMinute
, cTimeSeparator
,t
.wSecond
, cDecimalSeparator
, t
.wMilliseconds
);
1115 cp
= _stpcpy (cp
, szTime
);
1119 else if (_tcsicmp(ip
,_T("date")) ==0)
1123 GetDateFormat(LOCALE_USER_DEFAULT
, 0, NULL
, _T("ddd"), szDate
, sizeof (szDate
));
1124 cp
= _stpcpy (cp
, szDate
);
1125 cp
= _stpcpy (cp
, _T(" "));
1126 GetDateFormat(LOCALE_USER_DEFAULT
, DATE_SHORTDATE
, NULL
, NULL
, szDate
, sizeof (szDate
));
1127 cp
= _stpcpy (cp
, szDate
);
1131 else if (_tcsicmp(ip
,_T("random")) ==0)
1134 /* Get random number */
1135 _itot(rand(),szRand
,10);
1136 cp
= _stpcpy (cp
, szRand
);
1140 else if (_tcsicmp(ip
,_T("cmdcmdline")) ==0)
1143 /* Get random number */
1144 pargv
= GetCommandLine();
1145 cp
= _stpcpy (cp
, pargv
);
1148 /* %CMDEXTVERSION% */
1149 else if (_tcsicmp(ip
,_T("cmdextversion")) ==0)
1152 /* Set version number to 2 */
1154 cp
= _stpcpy (cp
, szVER
);
1158 else if (_tcsicmp(ip
,_T("errorlevel")) ==0)
1160 evar
= malloc ( size
* sizeof(TCHAR
));
1164 memset(evar
,0,512 * sizeof(TCHAR
));
1165 _itot(nErrorLevel
,evar
,10);
1166 cp
= _stpcpy (cp
, evar
);
1172 evar
= malloc ( 512 * sizeof(TCHAR
));
1176 size
= GetEnvironmentVariable (ip
, evar
, 512);
1177 if(GetLastError() == ERROR_ENVVAR_NOT_FOUND
)
1179 /* if no env var is found you must
1180 continue with what was input*/
1181 cp
= _stpcpy (cp
, _T("%"));
1182 cp
= _stpcpy (cp
, ip
);
1183 cp
= _stpcpy (cp
, _T("%"));
1189 evar
= realloc(evar
,size
* sizeof(TCHAR
) );
1194 size
= GetEnvironmentVariable (ip
, evar
, size
);
1199 cp
= _stpcpy (cp
, evar
);
1222 if (_istcntrl (*ip
))
1229 /* strip trailing spaces */
1230 while ((--cp
>= commandline
) && _istspace (*cp
));
1232 *(cp
+ 1) = _T('\0');
1235 /* Echo batch file line */
1239 ConOutPuts (commandline
);
1244 ParseCommandLine (commandline
);
1245 if (bEcho
&& !bIgnoreEcho
)
1247 bIgnoreEcho
= FALSE
;
1250 while (!bCanExit
|| !bExit
);
1257 * control-break handler.
1259 BOOL WINAPI
BreakHandler (DWORD dwCtrlType
)
1262 if ((dwCtrlType
!= CTRL_C_EVENT
) &&
1263 (dwCtrlType
!= CTRL_BREAK_EVENT
))
1266 if (bChildProcessRunning
== TRUE
)
1268 GenerateConsoleCtrlEvent (CTRL_C_EVENT
,
1273 /* FIXME: Handle batch files */
1275 /* FIXME: Print "^C" */
1282 VOID
AddBreakHandler (VOID
)
1284 SetConsoleCtrlHandler ((PHANDLER_ROUTINE
)BreakHandler
, TRUE
);
1288 VOID
RemoveBreakHandler (VOID
)
1290 SetConsoleCtrlHandler ((PHANDLER_ROUTINE
)BreakHandler
, FALSE
);
1295 * show commands and options that are available.
1302 /* print command list */
1303 ConOutResPuts(STRING_CMD_HELP1
);
1306 /* print feature list */
1307 ConOutResPuts(STRING_CMD_HELP2
);
1309 #ifdef FEATURE_ALIASES
1310 ConOutResPuts(STRING_CMD_HELP3
);
1312 #ifdef FEATURE_HISTORY
1313 ConOutResPuts(STRING_CMD_HELP4
);
1315 #ifdef FEATURE_UNIX_FILENAME_COMPLETION
1316 ConOutResPuts(STRING_CMD_HELP5
);
1318 #ifdef FEATURE_DIRECTORY_STACK
1319 ConOutResPuts(STRING_CMD_HELP6
);
1321 #ifdef FEATURE_REDIRECTION
1322 ConOutResPuts(STRING_CMD_HELP7
);
1324 ConOutChar(_T('\n'));
1329 * set up global initializations and process parameters
1331 * argc - number of parameters to command.com
1332 * argv - command-line parameters
1336 Initialize (int argc
, TCHAR
* argv
[])
1338 TCHAR commandline
[CMDLINE_LENGTH
];
1339 TCHAR ModuleName
[_MAX_PATH
+ 1];
1344 //TCHAR *ptr, *cmdLine;
1346 /* get version information */
1347 osvi
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
1348 GetVersionEx (&osvi
);
1350 /* Some people like to run ReactOS cmd.exe on Win98, it helps in the
1351 build process. So don't link implicitly against ntdll.dll, load it
1352 dynamically instead */
1354 if (osvi
.dwPlatformId
== VER_PLATFORM_WIN32_NT
)
1356 /* ntdll is always present on NT */
1357 NtDllModule
= GetModuleHandle(TEXT("ntdll.dll"));
1361 /* not all 9x versions have a ntdll.dll, try to load it */
1362 NtDllModule
= LoadLibrary(TEXT("ntdll.dll"));
1365 if (NtDllModule
!= NULL
)
1367 NtQueryInformationProcessPtr
= (NtQueryInformationProcessProc
)GetProcAddress(NtDllModule
, "NtQueryInformationProcess");
1368 NtReadVirtualMemoryPtr
= (NtReadVirtualMemoryProc
)GetProcAddress(NtDllModule
, "NtReadVirtualMemory");
1375 DebugPrintf (_T("[command args:\n"));
1376 for (x
= 0; x
< argc
; x
++)
1378 DebugPrintf (_T("%d. %s\n"), x
, argv
[x
]);
1380 DebugPrintf (_T("]\n"));
1385 /* get default input and output console handles */
1386 hOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
1387 hIn
= GetStdHandle (STD_INPUT_HANDLE
);
1389 /* Set EnvironmentVariable PROMPT if it does not exists any env value.
1390 for you can change the EnvirommentVariable for prompt before cmd start
1391 this patch are not 100% right, if it does not exists a PROMPT value cmd should use
1392 $P$G as defualt not set EnvirommentVariable PROMPT to $P$G if it does not exists */
1393 if (GetEnvironmentVariable(_T("PROMPT"),lpBuffer
, 2 * sizeof(TCHAR
)) == 0)
1394 SetEnvironmentVariable (_T("PROMPT"), _T("$P$G"));
1397 if (argc
>= 2 && !_tcsncmp (argv
[1], _T("/?"), 2))
1399 ConOutResPaging(TRUE
,STRING_CMD_HELP8
);
1402 SetConsoleMode (hIn
, ENABLE_PROCESSED_INPUT
);
1404 #ifdef INCLUDE_CMD_CHDIR
1408 #ifdef FATURE_ALIASES
1414 for (i
= 1; i
< argc
; i
++)
1416 if (!_tcsicmp (argv
[i
], _T("/p")))
1418 if (!IsExistingFile (_T("\\autoexec.bat")))
1420 #ifdef INCLUDE_CMD_DATE
1421 cmd_date (_T(""), _T(""));
1423 #ifdef INCLUDE_CMD_TIME
1424 cmd_time (_T(""), _T(""));
1429 ParseCommandLine (_T("\\autoexec.bat"));
1433 else if (!_tcsicmp (argv
[i
], _T("/c")))
1435 /* This just runs a program and exits */
1439 _tcscpy (commandline
, argv
[i
]);
1442 _tcscat (commandline
, _T(" "));
1443 _tcscat (commandline
, argv
[i
]);
1446 ParseCommandLine(commandline
);
1447 ExitProcess (ProcessInput (TRUE
));
1454 else if (!_tcsicmp (argv
[i
], _T("/k")))
1456 /* This just runs a program and remains */
1460 _tcscpy (commandline
, argv
[i
]);
1463 _tcscat (commandline
, _T(" "));
1464 _tcscat (commandline
, argv
[i
]);
1467 ParseCommandLine(commandline
);
1470 #ifdef INCLUDE_CMD_COLOR
1471 else if (!_tcsnicmp (argv
[i
], _T("/t:"), 3))
1473 /* process /t (color) argument */
1474 wDefColor
= (WORD
)_tcstoul (&argv
[i
][3], NULL
, 16);
1476 SetScreenColor (wColor
, TRUE
);
1482 /* run cmdstart.bat */
1483 if (IsExistingFile (_T("cmdstart.bat")))
1485 ParseCommandLine (_T("cmdstart.bat"));
1487 else if (IsExistingFile (_T("\\cmdstart.bat")))
1489 ParseCommandLine (_T("\\cmdstart.bat"));
1494 /* try to run cmdstart.bat from install dir */
1497 _tcscpy (commandline
, argv
[0]);
1498 p
= _tcsrchr (commandline
, _T('\\')) + 1;
1499 _tcscpy (p
, _T("cmdstart.bat"));
1501 if (IsExistingFile (_T("commandline")))
1503 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR4
, szMsg
, RC_STRING_MAX_SIZE
);
1504 ConErrPrintf(szMsg
, commandline
);
1505 ParseCommandLine (commandline
);
1510 #ifdef FEATURE_DIR_STACK
1511 /* initialize directory stack */
1512 InitDirectoryStack ();
1516 #ifdef FEATURE_HISTORY
1517 /*initialize history*/
1521 /* Set COMSPEC environment variable */
1522 if (0 != GetModuleFileName (NULL
, ModuleName
, _MAX_PATH
+ 1))
1524 ModuleName
[_MAX_PATH
] = _T('\0');
1525 SetEnvironmentVariable (_T("COMSPEC"), ModuleName
);
1528 /* add ctrl break handler */
1533 static VOID
Cleanup (int argc
, TCHAR
*argv
[])
1536 TCHAR szMsg
[RC_STRING_MAX_SIZE
];
1539 /* run cmdexit.bat */
1540 if (IsExistingFile (_T("cmdexit.bat")))
1542 ConErrResPuts(STRING_CMD_ERROR5
);
1544 ParseCommandLine (_T("cmdexit.bat"));
1546 else if (IsExistingFile (_T("\\cmdexit.bat")))
1548 ConErrResPuts (STRING_CMD_ERROR5
);
1549 ParseCommandLine (_T("\\cmdexit.bat"));
1554 /* try to run cmdexit.bat from install dir */
1555 TCHAR commandline
[CMDLINE_LENGTH
];
1558 _tcscpy (commandline
, argv
[0]);
1559 p
= _tcsrchr (commandline
, _T('\\')) + 1;
1560 _tcscpy (p
, _T("cmdexit.bat"));
1562 if (IsExistingFile (_T("commandline")))
1564 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR4
, szMsg
, RC_STRING_MAX_SIZE
);
1565 ConErrPrintf(szMsg
, commandline
);
1566 ParseCommandLine (commandline
);
1571 #ifdef FEATURE_ALIASES
1575 #ifdef FEATURE_DIECTORY_STACK
1576 /* destroy directory stack */
1577 DestroyDirectoryStack ();
1580 #ifdef INCLUDE_CMD_CHDIR
1584 #ifdef FEATURE_HISTORY
1589 /* remove ctrl break handler */
1590 RemoveBreakHandler ();
1591 SetConsoleMode( GetStdHandle( STD_INPUT_HANDLE
),
1592 ENABLE_LINE_INPUT
| ENABLE_PROCESSED_INPUT
| ENABLE_ECHO_INPUT
);
1594 if (NtDllModule
!= NULL
)
1596 FreeLibrary(NtDllModule
);
1602 PWCHAR
* _CommandLineToArgvW(PWCHAR lpCmdLine
, int *pNumArgs
)
1604 PWCHAR
* argvw
= NULL
;
1605 PWCHAR ptr
= lpCmdLine
;
1612 while(lpCmdLine
&& *lpCmdLine
)
1614 while (iswspace(*lpCmdLine
)) lpCmdLine
++;
1617 if ((NumArgs
% 10)==0)
1619 PWCHAR
* old_argvw
= argvw
;
1620 argvw
= malloc((NumArgs
+ 10) * sizeof(PWCHAR
));
1621 memcpy(argvw
, old_argvw
, NumArgs
* sizeof(PWCHAR
));
1624 ptr
= wcschr(lpCmdLine
, L
' ');
1627 len
= ptr
- lpCmdLine
;
1631 len
= wcslen(lpCmdLine
);
1633 str
= malloc((len
+ 1) * sizeof(WCHAR
));
1634 memcpy(str
, lpCmdLine
, len
* sizeof(WCHAR
));
1641 *pNumArgs
= NumArgs
;
1653 int _main (int argc
, char *argv
[])
1656 TCHAR startPath
[MAX_PATH
];
1657 CONSOLE_SCREEN_BUFFER_INFO Info
;
1663 argv
= _CommandLineToArgvW(GetCommandLineW(), &argc
);
1665 argv
= CommandLineToArgvW(GetCommandLineW(), &argc
);
1669 GetCurrentDirectory(MAX_PATH
,startPath
);
1676 hConsole
= CreateFile(_T("CONOUT$"), GENERIC_READ
|GENERIC_WRITE
,
1677 FILE_SHARE_READ
|FILE_SHARE_WRITE
, NULL
,
1678 OPEN_EXISTING
, 0, NULL
);
1679 if (GetConsoleScreenBufferInfo(hConsole
, &Info
) == FALSE
)
1681 ConErrFormatMessage(GetLastError());
1684 wColor
= Info
.wAttributes
;
1687 InputCodePage
= GetConsoleCP();
1688 OutputCodePage
= GetConsoleOutputCP();
1689 CMD_ModuleHandle
= GetModuleHandle(NULL
);
1691 /* check switches on command-line */
1692 Initialize(argc
, argv
);
1694 /* call prompt routine */
1695 nExitCode
= ProcessInput(FALSE
);
1698 /* do the cleanup */
1699 Cleanup(argc
, argv
);