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
];
304 DWORD dwExitCode
= 0;
307 DebugPrintf (_T("Execute: \'%s\' \'%s\'\n"), first
, rest
);
310 /* we need biger buffer that First, Rest, Full are already
311 need rewrite some code to use realloc when it need instead
312 of add 512bytes extra */
314 first
= malloc ( (_tcslen(First
) + 512) * sizeof(TCHAR
));
317 error_out_of_memory();
321 rest
= malloc ( (_tcslen(Rest
) + 512) * sizeof(TCHAR
));
325 error_out_of_memory();
329 full
= malloc ( (_tcslen(Full
) + 512) * sizeof(TCHAR
));
334 error_out_of_memory();
339 /* Though it was already parsed once, we have a different set of rules
340 for parsing before we pass to CreateProccess */
341 if(!_tcschr(Full
,_T('\"')))
343 _tcscpy(first
,First
);
350 BOOL bInside
= FALSE
;
355 /* find the end of the command and start of the args */
356 for(i
= 0; i
< _tcslen(first
); i
++)
358 if(!_tcsncmp(&first
[i
], _T("\""), 1))
360 if(!_tcsncmp(&first
[i
], _T(" "), 1) && !bInside
)
362 _tcscpy(rest
,&first
[i
]);
369 /* remove any slashes */
370 while(i
< _tcslen(first
))
372 if(first
[i
] == _T('\"'))
373 memmove(&first
[i
],&first
[i
+ 1], _tcslen(&first
[i
]) * sizeof(TCHAR
));
377 /* Drop quotes around it just in case there is a space */
378 _tcscpy(full
,_T("\""));
380 _tcscat(full
,_T("\" "));
384 /* check for a drive change */
385 if ((_istalpha (first
[0])) && (!_tcscmp (first
+ 1, _T(":"))))
388 if (!SetCurrentDirectory(first
))
389 /* Guess they changed disc or something, handle that gracefully and get to root */
396 working
= SetCurrentDirectory(str
);
399 if (!working
) ConErrResPuts (STRING_FREE_ERROR1
);
404 /* get the PATH environment variable and parse it */
405 /* search the PATH environment variable for the binary */
406 if (!SearchForExecutable (first
, szFullName
))
408 error_bad_command ();
412 GetConsoleTitle (szWindowTitle
, MAX_PATH
);
414 /* check if this is a .BAT or .CMD file */
415 dot
= _tcsrchr (szFullName
, _T('.'));
416 if (dot
&& (!_tcsicmp (dot
, _T(".bat")) || !_tcsicmp (dot
, _T(".cmd"))))
419 DebugPrintf (_T("[BATCH: %s %s]\n"), szFullName
, rest
);
421 Batch (szFullName
, first
, rest
);
425 /* exec the program */
426 PROCESS_INFORMATION prci
;
430 DebugPrintf (_T("[EXEC: %s %s]\n"), full
, rest
);
432 /* build command line for CreateProcess() */
434 /* fill startup info */
435 memset (&stui
, 0, sizeof (STARTUPINFO
));
436 stui
.cb
= sizeof (STARTUPINFO
);
437 stui
.dwFlags
= STARTF_USESHOWWINDOW
;
438 stui
.wShowWindow
= SW_SHOWDEFAULT
;
440 // return console to standard mode
441 SetConsoleMode (GetStdHandle(STD_INPUT_HANDLE
),
442 ENABLE_LINE_INPUT
| ENABLE_PROCESSED_INPUT
| ENABLE_ECHO_INPUT
);
444 if (CreateProcess (szFullName
,
449 CREATE_NEW_PROCESS_GROUP
,
455 if (IsConsoleProcess(prci
.hProcess
))
457 /* FIXME: Protect this with critical section */
458 bChildProcessRunning
= TRUE
;
459 dwChildProcessId
= prci
.dwProcessId
;
461 WaitForSingleObject (prci
.hProcess
, INFINITE
);
463 /* FIXME: Protect this with critical section */
464 bChildProcessRunning
= FALSE
;
466 GetExitCodeProcess (prci
.hProcess
, &dwExitCode
);
467 nErrorLevel
= (INT
)dwExitCode
;
469 CloseHandle (prci
.hThread
);
470 CloseHandle (prci
.hProcess
);
475 DebugPrintf (_T("[ShellExecute: %s]\n"), full
);
477 // See if we can run this with ShellExecute() ie myfile.xls
481 DebugPrintf (_T("[ShellExecute failed!: %s]\n"), full
);
483 error_bad_command ();
486 // restore console mode
487 SetConsoleMode( GetStdHandle( STD_INPUT_HANDLE
),
488 ENABLE_PROCESSED_INPUT
);
491 /* Get code page if it has been change */
492 InputCodePage
= GetConsoleCP();
493 OutputCodePage
= GetConsoleOutputCP();
494 SetConsoleTitle (szWindowTitle
);
503 * look through the internal commands and determine whether or not this
504 * command is one of them. If it is, call the command. If not, call
505 * execute to run it as an external program.
507 * line - the command line of the program to run
512 DoCommand (LPTSTR line
)
514 TCHAR com
[CMDLINE_LENGTH
]; /* the first word in the command */
517 LPTSTR rest
; /* pointer to the rest of the command line */
522 DebugPrintf (_T("DoCommand: (\'%s\')\n"), line
);
525 /* Skip over initial white space */
526 while (_istspace (*line
))
532 /* Anything to do ? */
535 if (*rest
== _T('"'))
537 /* treat quoted words specially */
541 while(*rest
!= _T('\0') && *rest
!= _T('"'))
542 *cp
++ = _totlower (*rest
++);
543 if (*rest
== _T('"'))
548 while (!IsDelimiter (*rest
))
549 *cp
++ = _totlower (*rest
++);
553 /* Terminate first word */
556 /* commands are limited to MAX_PATH */
557 if(_tcslen(com
) > MAX_PATH
)
563 /* Skip over whitespace to rest of line */
564 while (_istspace (*rest
))
567 /* Scan internal command table */
568 for (cmdptr
= cmds
;; cmdptr
++)
570 /* If end of table execute ext cmd */
571 if (cmdptr
->name
== NULL
)
573 Execute (line
, com
, rest
);
577 if (!_tcscmp (com
, cmdptr
->name
))
579 cmdptr
->func (com
, rest
);
583 /* The following code handles the case of commands like CD which
584 * are recognised even when the command name and parameter are
585 * not space separated.
591 /* Get length of command name */
592 cl
= _tcslen (cmdptr
->name
);
594 if ((cmdptr
->flags
& CMD_SPECIAL
) &&
595 (!_tcsncmp (cmdptr
->name
, com
, cl
)) &&
596 (_tcschr (_T("\\.-"), *(com
+ cl
))))
598 /* OK its one of the specials...*/
600 /* Terminate first word properly */
603 /* Call with new rest */
604 cmdptr
->func (com
, cstart
+ cl
);
613 * process the command line and execute the appropriate functions
614 * full input/output redirection and piping are supported
617 VOID
ParseCommandLine (LPTSTR cmd
)
619 TCHAR szMsg
[RC_STRING_MAX_SIZE
];
620 TCHAR cmdline
[CMDLINE_LENGTH
];
622 #ifdef FEATURE_REDIRECTION
623 TCHAR in
[CMDLINE_LENGTH
] = _T("");
624 TCHAR out
[CMDLINE_LENGTH
] = _T("");
625 TCHAR err
[CMDLINE_LENGTH
] = _T("");
626 TCHAR szTempPath
[MAX_PATH
] = _T(".\\");
627 TCHAR szFileName
[2][MAX_PATH
] = {_T(""), _T("")};
628 HANDLE hFile
[2] = {INVALID_HANDLE_VALUE
, INVALID_HANDLE_VALUE
};
634 BOOL bNewBatch
= TRUE
;
638 #endif /* FEATURE_REDIRECTION */
640 _tcscpy (cmdline
, cmd
);
644 DebugPrintf (_T("ParseCommandLine: (\'%s\')\n"), s
);
647 #ifdef FEATURE_ALIASES
648 /* expand all aliases */
649 ExpandAlias (s
, CMDLINE_LENGTH
);
650 #endif /* FEATURE_ALIAS */
652 #ifdef FEATURE_REDIRECTION
653 /* find the temp path to store temporary files */
654 Length
= GetTempPath (MAX_PATH
, szTempPath
);
655 if (Length
> 0 && Length
< MAX_PATH
)
657 Attributes
= GetFileAttributes(szTempPath
);
658 if (Attributes
== 0xffffffff ||
659 !(Attributes
& FILE_ATTRIBUTE_DIRECTORY
))
664 if (Length
== 0 || Length
>= MAX_PATH
)
666 _tcscpy(szTempPath
, _T(".\\"));
668 if (szTempPath
[_tcslen (szTempPath
) - 1] != _T('\\'))
669 _tcscat (szTempPath
, _T("\\"));
671 /* get the redirections from the command line */
672 num
= GetRedirection (s
, in
, out
, err
, &nRedirFlags
);
674 /* more efficient, but do we really need to do this? */
675 for (t
= in
; _istspace (*t
); t
++)
679 for (t
= out
; _istspace (*t
); t
++)
683 for (t
= err
; _istspace (*t
); t
++)
687 if(bc
&& !_tcslen (in
) && _tcslen (bc
->In
))
689 if(bc
&& !out
[0] && _tcslen(bc
->Out
))
691 nRedirFlags
|= OUTPUT_APPEND
;
692 _tcscpy(out
, bc
->Out
);
694 if(bc
&& !_tcslen (err
) && _tcslen (bc
->Err
))
696 nRedirFlags
|= ERROR_APPEND
;
697 _tcscpy(err
, bc
->Err
);
701 /* Set up the initial conditions ... */
702 /* preserve STDIN, STDOUT and STDERR handles */
703 hOldConIn
= GetStdHandle (STD_INPUT_HANDLE
);
704 hOldConOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
705 hOldConErr
= GetStdHandle (STD_ERROR_HANDLE
);
711 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
713 /* we need make sure the LastError msg is zero before calling CreateFile */
716 /* Set up pipe for the standard input handler */
717 hFile
= CreateFile (in
, GENERIC_READ
, FILE_SHARE_READ
, &sa
, OPEN_EXISTING
,
718 FILE_ATTRIBUTE_NORMAL
, NULL
);
719 if (hFile
== INVALID_HANDLE_VALUE
)
721 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR1
, szMsg
, RC_STRING_MAX_SIZE
);
722 ConErrPrintf(szMsg
, in
);
726 if (!SetStdHandle (STD_INPUT_HANDLE
, hFile
))
728 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR1
, szMsg
, RC_STRING_MAX_SIZE
);
729 ConErrPrintf(szMsg
, in
);
733 DebugPrintf (_T("Input redirected from: %s\n"), in
);
737 /* Now do all but the last pipe command */
738 *szFileName
[0] = _T('\0');
739 hFile
[0] = INVALID_HANDLE_VALUE
;
743 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
745 /* Create unique temporary file name */
746 GetTempFileName (szTempPath
, _T("CMD"), 0, szFileName
[1]);
748 /* we need make sure the LastError msg is zero before calling CreateFile */
751 /* Set current stdout to temporary file */
752 hFile
[1] = CreateFile (szFileName
[1], GENERIC_WRITE
, 0, &sa
,
753 TRUNCATE_EXISTING
, FILE_ATTRIBUTE_TEMPORARY
, NULL
);
755 if (hFile
[1] == INVALID_HANDLE_VALUE
)
757 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR2
, szMsg
, RC_STRING_MAX_SIZE
);
762 SetStdHandle (STD_OUTPUT_HANDLE
, hFile
[1]);
766 /* close stdout file */
767 SetStdHandle (STD_OUTPUT_HANDLE
, hOldConOut
);
768 if ((hFile
[1] != INVALID_HANDLE_VALUE
) && (hFile
[1] != hOldConOut
))
770 CloseHandle (hFile
[1]);
771 hFile
[1] = INVALID_HANDLE_VALUE
;
774 /* close old stdin file */
775 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
776 if ((hFile
[0] != INVALID_HANDLE_VALUE
) && (hFile
[0] != hOldConIn
))
778 /* delete old stdin file, if it is a real file */
779 CloseHandle (hFile
[0]);
780 hFile
[0] = INVALID_HANDLE_VALUE
;
781 DeleteFile (szFileName
[0]);
782 *szFileName
[0] = _T('\0');
785 /* copy stdout file name to stdin file name */
786 _tcscpy (szFileName
[0], szFileName
[1]);
787 *szFileName
[1] = _T('\0');
789 /* we need make sure the LastError msg is zero before calling CreateFile */
792 /* open new stdin file */
793 hFile
[0] = CreateFile (szFileName
[0], GENERIC_READ
, 0, &sa
,
794 OPEN_EXISTING
, FILE_ATTRIBUTE_TEMPORARY
, NULL
);
795 SetStdHandle (STD_INPUT_HANDLE
, hFile
[0]);
797 s
= s
+ _tcslen (s
) + 1;
800 /* Now set up the end conditions... */
801 /* redirect STDOUT */
804 /* Final output to here */
806 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
808 /* we need make sure the LastError msg is zero before calling CreateFile */
811 hFile
= CreateFile (out
, GENERIC_WRITE
, FILE_SHARE_WRITE
| FILE_SHARE_READ
| FILE_SHARE_DELETE
, &sa
,
812 (nRedirFlags
& OUTPUT_APPEND
) ? OPEN_ALWAYS
: CREATE_ALWAYS
,
813 FILE_ATTRIBUTE_NORMAL
| FILE_FLAG_WRITE_THROUGH
, NULL
);
815 if (hFile
== INVALID_HANDLE_VALUE
)
817 INT size
= _tcslen(out
)-1;
819 if (out
[size
] != _T(':'))
821 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR3
, szMsg
, RC_STRING_MAX_SIZE
);
822 ConErrPrintf(szMsg
, out
);
827 hFile
= CreateFile (out
, GENERIC_WRITE
, FILE_SHARE_WRITE
| FILE_SHARE_READ
| FILE_SHARE_DELETE
, &sa
,
828 (nRedirFlags
& OUTPUT_APPEND
) ? OPEN_ALWAYS
: CREATE_ALWAYS
,
829 FILE_ATTRIBUTE_NORMAL
| FILE_FLAG_WRITE_THROUGH
, NULL
);
831 if (hFile
== INVALID_HANDLE_VALUE
)
833 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR3
, szMsg
, RC_STRING_MAX_SIZE
);
834 ConErrPrintf(szMsg
, out
);
840 if (!SetStdHandle (STD_OUTPUT_HANDLE
, hFile
))
842 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR3
, szMsg
, RC_STRING_MAX_SIZE
);
843 ConErrPrintf(szMsg
, out
);
847 if (nRedirFlags
& OUTPUT_APPEND
)
851 if (GetFileType (hFile
) == FILE_TYPE_DISK
)
852 SetFilePointer (hFile
, 0, &lHighPos
, FILE_END
);
855 DebugPrintf (_T("Output redirected to: %s\n"), out
);
858 else if (hOldConOut
!= INVALID_HANDLE_VALUE
)
860 /* Restore original stdout */
861 HANDLE hOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
862 SetStdHandle (STD_OUTPUT_HANDLE
, hOldConOut
);
863 if (hOldConOut
!= hOut
)
865 hOldConOut
= INVALID_HANDLE_VALUE
;
868 /* redirect STDERR */
871 /* Final output to here */
873 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
875 if (!_tcscmp (err
, out
))
878 DebugPrintf (_T("Stdout and stderr will use the same file!!\n"));
880 DuplicateHandle (GetCurrentProcess (),
881 GetStdHandle (STD_OUTPUT_HANDLE
),
882 GetCurrentProcess (),
883 &hFile
, 0, TRUE
, DUPLICATE_SAME_ACCESS
);
887 hFile
= CreateFile (err
,
889 FILE_SHARE_WRITE
| FILE_SHARE_READ
| FILE_SHARE_DELETE
,
891 (nRedirFlags
& ERROR_APPEND
) ? OPEN_ALWAYS
: CREATE_ALWAYS
,
892 FILE_ATTRIBUTE_NORMAL
| FILE_FLAG_WRITE_THROUGH
,
894 if (hFile
== INVALID_HANDLE_VALUE
)
896 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR3
, szMsg
, RC_STRING_MAX_SIZE
);
897 ConErrPrintf(szMsg
, err
);
902 if (!SetStdHandle (STD_ERROR_HANDLE
, hFile
))
904 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR3
, szMsg
, RC_STRING_MAX_SIZE
);
905 ConErrPrintf(szMsg
, err
);
909 if (nRedirFlags
& ERROR_APPEND
)
913 if (GetFileType (hFile
) == FILE_TYPE_DISK
)
914 SetFilePointer (hFile
, 0, &lHighPos
, FILE_END
);
917 DebugPrintf (_T("Error redirected to: %s\n"), err
);
920 else if (hOldConErr
!= INVALID_HANDLE_VALUE
)
922 /* Restore original stderr */
923 HANDLE hErr
= GetStdHandle (STD_ERROR_HANDLE
);
924 SetStdHandle (STD_ERROR_HANDLE
, hOldConErr
);
925 if (hOldConErr
!= hErr
)
927 hOldConErr
= INVALID_HANDLE_VALUE
;
934 /* process final command */
937 #ifdef FEATURE_REDIRECTION
939 AddBatchRedirection(in
, out
, err
);
940 /* close old stdin file */
941 #if 0 /* buggy implementation */
942 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
943 if ((hFile
[0] != INVALID_HANDLE_VALUE
) &&
944 (hFile
[0] != hOldConIn
))
946 /* delete old stdin file, if it is a real file */
947 CloseHandle (hFile
[0]);
948 hFile
[0] = INVALID_HANDLE_VALUE
;
949 DeleteFile (szFileName
[0]);
950 *szFileName
[0] = _T('\0');
953 /* Restore original STDIN */
954 if (hOldConIn
!= INVALID_HANDLE_VALUE
)
956 HANDLE hIn
= GetStdHandle (STD_INPUT_HANDLE
);
957 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
958 if (hOldConIn
!= hIn
)
960 hOldConIn
= INVALID_HANDLE_VALUE
;
965 DebugPrintf (_T("Can't restore STDIN! Is invalid!!\n"), out
);
968 #endif /* buggy implementation */
971 if (hOldConIn
!= INVALID_HANDLE_VALUE
)
973 HANDLE hIn
= GetStdHandle (STD_INPUT_HANDLE
);
974 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
975 if (hIn
== INVALID_HANDLE_VALUE
)
978 DebugPrintf (_T("Previous STDIN is invalid!!\n"));
983 if (GetFileType (hIn
) == FILE_TYPE_DISK
)
987 CloseHandle (hFile
[0]);
988 hFile
[0] = INVALID_HANDLE_VALUE
;
989 DeleteFile (szFileName
[0]);
990 *szFileName
[0] = _T('\0');
995 DebugPrintf (_T("hFile[0] and hIn dont match!!!\n"));
1003 /* Restore original STDOUT */
1004 if (hOldConOut
!= INVALID_HANDLE_VALUE
)
1006 HANDLE hOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
1007 SetStdHandle (STD_OUTPUT_HANDLE
, hOldConOut
);
1008 if (hOldConOut
!= hOut
)
1010 hOldConOut
= INVALID_HANDLE_VALUE
;
1013 /* Restore original STDERR */
1014 if (hOldConErr
!= INVALID_HANDLE_VALUE
)
1016 HANDLE hErr
= GetStdHandle (STD_ERROR_HANDLE
);
1017 SetStdHandle (STD_ERROR_HANDLE
, hOldConErr
);
1018 if (hOldConErr
!= hErr
)
1020 hOldConErr
= INVALID_HANDLE_VALUE
;
1022 #endif /* FEATURE_REDIRECTION */
1027 * do the prompt/input/process loop
1032 ProcessInput (BOOL bFlag
)
1034 TCHAR commandline
[CMDLINE_LENGTH
];
1035 TCHAR readline
[CMDLINE_LENGTH
];
1044 /* if no batch input then... */
1045 if (!(ip
= ReadBatchLine (&bEchoThisLine
)))
1050 ReadCommand (readline
, CMDLINE_LENGTH
);
1052 bEchoThisLine
= FALSE
;
1076 if ((tp
= FindArg (*ip
- _T('0'))))
1078 cp
= _stpcpy (cp
, tp
);
1086 cp
+= _stprintf (cp
, _T("%u"), nErrorLevel
);
1091 tp
= _tcschr(ip
, _T('%'));
1093 (tp
<= _tcschr(ip
, _T(' ')) - 1))
1099 /* FIXME: Correct error handling when it can not alloc memmory */
1102 if (_tcsicmp(ip
,_T("cd")) ==0)
1104 TCHAR szPath
[MAX_PATH
];
1105 GetCurrentDirectory (MAX_PATH
, szPath
);
1106 cp
= _stpcpy (cp
, szPath
);
1109 else if (_tcsicmp(ip
,_T("time")) ==0)
1115 _sntprintf(szTime
,40,_T("%02d%c%02d%c%02d%c%02d"), t
.wHour
, cTimeSeparator
,t
.wMinute
, cTimeSeparator
,t
.wSecond
, cDecimalSeparator
, t
.wMilliseconds
);
1116 cp
= _stpcpy (cp
, szTime
);
1120 else if (_tcsicmp(ip
,_T("date")) ==0)
1124 GetDateFormat(LOCALE_USER_DEFAULT
, 0, NULL
, _T("ddd"), szDate
, sizeof (szDate
));
1125 cp
= _stpcpy (cp
, szDate
);
1126 cp
= _stpcpy (cp
, _T(" "));
1127 GetDateFormat(LOCALE_USER_DEFAULT
, DATE_SHORTDATE
, NULL
, NULL
, szDate
, sizeof (szDate
));
1128 cp
= _stpcpy (cp
, szDate
);
1132 else if (_tcsicmp(ip
,_T("random")) ==0)
1135 /* Get random number */
1136 _itot(rand(),szRand
,10);
1137 cp
= _stpcpy (cp
, szRand
);
1141 else if (_tcsicmp(ip
,_T("cmdcmdline")) ==0)
1144 /* Get random number */
1145 pargv
= GetCommandLine();
1146 cp
= _stpcpy (cp
, pargv
);
1149 /* %CMDEXTVERSION% */
1150 else if (_tcsicmp(ip
,_T("cmdextversion")) ==0)
1153 /* Set version number to 2 */
1155 cp
= _stpcpy (cp
, szVER
);
1159 else if (_tcsicmp(ip
,_T("errorlevel")) ==0)
1161 evar
= malloc ( size
* sizeof(TCHAR
));
1165 memset(evar
,0,512 * sizeof(TCHAR
));
1166 _itot(nErrorLevel
,evar
,10);
1167 cp
= _stpcpy (cp
, evar
);
1173 evar
= malloc ( 512 * sizeof(TCHAR
));
1177 size
= GetEnvironmentVariable (ip
, evar
, 512);
1178 if(GetLastError() == ERROR_ENVVAR_NOT_FOUND
)
1180 /* if no env var is found you must
1181 continue with what was input*/
1182 cp
= _stpcpy (cp
, _T("%"));
1183 cp
= _stpcpy (cp
, ip
);
1184 cp
= _stpcpy (cp
, _T("%"));
1190 evar
= realloc(evar
,size
* sizeof(TCHAR
) );
1195 size
= GetEnvironmentVariable (ip
, evar
, size
);
1200 cp
= _stpcpy (cp
, evar
);
1223 if (_istcntrl (*ip
))
1230 /* strip trailing spaces */
1231 while ((--cp
>= commandline
) && _istspace (*cp
));
1233 *(cp
+ 1) = _T('\0');
1236 /* Echo batch file line */
1240 ConOutPuts (commandline
);
1245 ParseCommandLine (commandline
);
1246 if (bEcho
&& !bIgnoreEcho
)
1248 bIgnoreEcho
= FALSE
;
1251 while (!bCanExit
|| !bExit
);
1258 * control-break handler.
1260 BOOL WINAPI
BreakHandler (DWORD dwCtrlType
)
1263 if ((dwCtrlType
!= CTRL_C_EVENT
) &&
1264 (dwCtrlType
!= CTRL_BREAK_EVENT
))
1267 if (bChildProcessRunning
== TRUE
)
1269 GenerateConsoleCtrlEvent (CTRL_C_EVENT
,
1274 /* FIXME: Handle batch files */
1276 /* FIXME: Print "^C" */
1283 VOID
AddBreakHandler (VOID
)
1285 SetConsoleCtrlHandler ((PHANDLER_ROUTINE
)BreakHandler
, TRUE
);
1289 VOID
RemoveBreakHandler (VOID
)
1291 SetConsoleCtrlHandler ((PHANDLER_ROUTINE
)BreakHandler
, FALSE
);
1296 * show commands and options that are available.
1303 /* print command list */
1304 ConOutResPuts(STRING_CMD_HELP1
);
1307 /* print feature list */
1308 ConOutResPuts(STRING_CMD_HELP2
);
1310 #ifdef FEATURE_ALIASES
1311 ConOutResPuts(STRING_CMD_HELP3
);
1313 #ifdef FEATURE_HISTORY
1314 ConOutResPuts(STRING_CMD_HELP4
);
1316 #ifdef FEATURE_UNIX_FILENAME_COMPLETION
1317 ConOutResPuts(STRING_CMD_HELP5
);
1319 #ifdef FEATURE_DIRECTORY_STACK
1320 ConOutResPuts(STRING_CMD_HELP6
);
1322 #ifdef FEATURE_REDIRECTION
1323 ConOutResPuts(STRING_CMD_HELP7
);
1325 ConOutChar(_T('\n'));
1330 * set up global initializations and process parameters
1332 * argc - number of parameters to command.com
1333 * argv - command-line parameters
1337 Initialize (int argc
, TCHAR
* argv
[])
1339 TCHAR commandline
[CMDLINE_LENGTH
];
1340 TCHAR ModuleName
[_MAX_PATH
+ 1];
1345 //TCHAR *ptr, *cmdLine;
1347 /* get version information */
1348 osvi
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
1349 GetVersionEx (&osvi
);
1351 /* Some people like to run ReactOS cmd.exe on Win98, it helps in the
1352 build process. So don't link implicitly against ntdll.dll, load it
1353 dynamically instead */
1355 if (osvi
.dwPlatformId
== VER_PLATFORM_WIN32_NT
)
1357 /* ntdll is always present on NT */
1358 NtDllModule
= GetModuleHandle(TEXT("ntdll.dll"));
1362 /* not all 9x versions have a ntdll.dll, try to load it */
1363 NtDllModule
= LoadLibrary(TEXT("ntdll.dll"));
1366 if (NtDllModule
!= NULL
)
1368 NtQueryInformationProcessPtr
= (NtQueryInformationProcessProc
)GetProcAddress(NtDllModule
, "NtQueryInformationProcess");
1369 NtReadVirtualMemoryPtr
= (NtReadVirtualMemoryProc
)GetProcAddress(NtDllModule
, "NtReadVirtualMemory");
1376 DebugPrintf (_T("[command args:\n"));
1377 for (x
= 0; x
< argc
; x
++)
1379 DebugPrintf (_T("%d. %s\n"), x
, argv
[x
]);
1381 DebugPrintf (_T("]\n"));
1386 /* get default input and output console handles */
1387 hOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
1388 hIn
= GetStdHandle (STD_INPUT_HANDLE
);
1390 /* Set EnvironmentVariable PROMPT if it does not exists any env value.
1391 for you can change the EnvirommentVariable for prompt before cmd start
1392 this patch are not 100% right, if it does not exists a PROMPT value cmd should use
1393 $P$G as defualt not set EnvirommentVariable PROMPT to $P$G if it does not exists */
1394 if (GetEnvironmentVariable(_T("PROMPT"),lpBuffer
, 2 * sizeof(TCHAR
)) == 0)
1395 SetEnvironmentVariable (_T("PROMPT"), _T("$P$G"));
1398 if (argc
>= 2 && !_tcsncmp (argv
[1], _T("/?"), 2))
1400 ConOutResPaging(TRUE
,STRING_CMD_HELP8
);
1403 SetConsoleMode (hIn
, ENABLE_PROCESSED_INPUT
);
1405 #ifdef INCLUDE_CMD_CHDIR
1409 #ifdef FATURE_ALIASES
1415 for (i
= 1; i
< argc
; i
++)
1417 if (!_tcsicmp (argv
[i
], _T("/p")))
1419 if (!IsExistingFile (_T("\\autoexec.bat")))
1421 #ifdef INCLUDE_CMD_DATE
1422 cmd_date (_T(""), _T(""));
1424 #ifdef INCLUDE_CMD_TIME
1425 cmd_time (_T(""), _T(""));
1430 ParseCommandLine (_T("\\autoexec.bat"));
1434 else if (!_tcsicmp (argv
[i
], _T("/c")))
1436 /* This just runs a program and exits */
1440 _tcscpy (commandline
, argv
[i
]);
1443 _tcscat (commandline
, _T(" "));
1444 _tcscat (commandline
, argv
[i
]);
1447 ParseCommandLine(commandline
);
1448 ExitProcess (ProcessInput (TRUE
));
1455 else if (!_tcsicmp (argv
[i
], _T("/k")))
1457 /* This just runs a program and remains */
1461 _tcscpy (commandline
, argv
[i
]);
1464 _tcscat (commandline
, _T(" "));
1465 _tcscat (commandline
, argv
[i
]);
1468 ParseCommandLine(commandline
);
1471 #ifdef INCLUDE_CMD_COLOR
1472 else if (!_tcsnicmp (argv
[i
], _T("/t:"), 3))
1474 /* process /t (color) argument */
1475 wDefColor
= (WORD
)_tcstoul (&argv
[i
][3], NULL
, 16);
1477 SetScreenColor (wColor
, TRUE
);
1483 /* run cmdstart.bat */
1484 if (IsExistingFile (_T("cmdstart.bat")))
1486 ParseCommandLine (_T("cmdstart.bat"));
1488 else if (IsExistingFile (_T("\\cmdstart.bat")))
1490 ParseCommandLine (_T("\\cmdstart.bat"));
1495 /* try to run cmdstart.bat from install dir */
1498 _tcscpy (commandline
, argv
[0]);
1499 p
= _tcsrchr (commandline
, _T('\\')) + 1;
1500 _tcscpy (p
, _T("cmdstart.bat"));
1502 if (IsExistingFile (_T("commandline")))
1504 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR4
, szMsg
, RC_STRING_MAX_SIZE
);
1505 ConErrPrintf(szMsg
, commandline
);
1506 ParseCommandLine (commandline
);
1511 #ifdef FEATURE_DIR_STACK
1512 /* initialize directory stack */
1513 InitDirectoryStack ();
1517 #ifdef FEATURE_HISTORY
1518 /*initialize history*/
1522 /* Set COMSPEC environment variable */
1523 if (0 != GetModuleFileName (NULL
, ModuleName
, _MAX_PATH
+ 1))
1525 ModuleName
[_MAX_PATH
] = _T('\0');
1526 SetEnvironmentVariable (_T("COMSPEC"), ModuleName
);
1529 /* add ctrl break handler */
1534 static VOID
Cleanup (int argc
, TCHAR
*argv
[])
1537 TCHAR szMsg
[RC_STRING_MAX_SIZE
];
1540 /* run cmdexit.bat */
1541 if (IsExistingFile (_T("cmdexit.bat")))
1543 ConErrResPuts(STRING_CMD_ERROR5
);
1545 ParseCommandLine (_T("cmdexit.bat"));
1547 else if (IsExistingFile (_T("\\cmdexit.bat")))
1549 ConErrResPuts (STRING_CMD_ERROR5
);
1550 ParseCommandLine (_T("\\cmdexit.bat"));
1555 /* try to run cmdexit.bat from install dir */
1556 TCHAR commandline
[CMDLINE_LENGTH
];
1559 _tcscpy (commandline
, argv
[0]);
1560 p
= _tcsrchr (commandline
, _T('\\')) + 1;
1561 _tcscpy (p
, _T("cmdexit.bat"));
1563 if (IsExistingFile (_T("commandline")))
1565 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR4
, szMsg
, RC_STRING_MAX_SIZE
);
1566 ConErrPrintf(szMsg
, commandline
);
1567 ParseCommandLine (commandline
);
1572 #ifdef FEATURE_ALIASES
1576 #ifdef FEATURE_DIECTORY_STACK
1577 /* destroy directory stack */
1578 DestroyDirectoryStack ();
1581 #ifdef INCLUDE_CMD_CHDIR
1585 #ifdef FEATURE_HISTORY
1590 /* remove ctrl break handler */
1591 RemoveBreakHandler ();
1592 SetConsoleMode( GetStdHandle( STD_INPUT_HANDLE
),
1593 ENABLE_LINE_INPUT
| ENABLE_PROCESSED_INPUT
| ENABLE_ECHO_INPUT
);
1595 if (NtDllModule
!= NULL
)
1597 FreeLibrary(NtDllModule
);
1603 PWCHAR
* _CommandLineToArgvW(PWCHAR lpCmdLine
, int *pNumArgs
)
1605 PWCHAR
* argvw
= NULL
;
1606 PWCHAR ptr
= lpCmdLine
;
1613 while(lpCmdLine
&& *lpCmdLine
)
1615 while (iswspace(*lpCmdLine
)) lpCmdLine
++;
1618 if ((NumArgs
% 10)==0)
1620 PWCHAR
* old_argvw
= argvw
;
1621 argvw
= malloc((NumArgs
+ 10) * sizeof(PWCHAR
));
1622 memcpy(argvw
, old_argvw
, NumArgs
* sizeof(PWCHAR
));
1625 ptr
= wcschr(lpCmdLine
, L
' ');
1628 len
= ptr
- lpCmdLine
;
1632 len
= wcslen(lpCmdLine
);
1634 str
= malloc((len
+ 1) * sizeof(WCHAR
));
1635 memcpy(str
, lpCmdLine
, len
* sizeof(WCHAR
));
1642 *pNumArgs
= NumArgs
;
1654 int _main (int argc
, char *argv
[])
1657 TCHAR startPath
[MAX_PATH
];
1658 CONSOLE_SCREEN_BUFFER_INFO Info
;
1664 argv
= _CommandLineToArgvW(GetCommandLineW(), &argc
);
1666 argv
= CommandLineToArgvW(GetCommandLineW(), &argc
);
1670 GetCurrentDirectory(MAX_PATH
,startPath
);
1677 hConsole
= CreateFile(_T("CONOUT$"), GENERIC_READ
|GENERIC_WRITE
,
1678 FILE_SHARE_READ
|FILE_SHARE_WRITE
, NULL
,
1679 OPEN_EXISTING
, 0, NULL
);
1680 if (GetConsoleScreenBufferInfo(hConsole
, &Info
) == FALSE
)
1682 ConErrFormatMessage(GetLastError());
1685 wColor
= Info
.wAttributes
;
1688 InputCodePage
= GetConsoleCP();
1689 OutputCodePage
= GetConsoleOutputCP();
1690 CMD_ModuleHandle
= GetModuleHandle(NULL
);
1692 /* check switches on command-line */
1693 Initialize(argc
, argv
);
1695 /* call prompt routine */
1696 nExitCode
= ProcessInput(FALSE
);
1699 /* do the cleanup */
1700 Cleanup(argc
, argv
);