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
];
299 TCHAR first
[CMDLINE_LENGTH
];
300 TCHAR rest
[CMDLINE_LENGTH
];
301 TCHAR full
[CMDLINE_LENGTH
];
303 TCHAR szWindowTitle
[MAX_PATH
];
305 DWORD dwExitCode
= 0;
308 DebugPrintf (_T("Execute: \'%s\' \'%s\'\n"), first
, rest
);
311 /* Though it was already parsed once, we have a different set of rules
312 for parsing before we pass to CreateProccess */
313 if(!_tcschr(Full
,_T('\"')))
315 _tcscpy(first
,First
);
322 BOOL bInside
= FALSE
;
327 /* find the end of the command and start of the args */
328 for(i
= 0; i
< _tcslen(first
); i
++)
330 if(!_tcsncmp(&first
[i
], _T("\""), 1))
332 if(!_tcsncmp(&first
[i
], _T(" "), 1) && !bInside
)
334 _tcscpy(rest
,&first
[i
]);
341 /* remove any slashes */
342 while(i
< _tcslen(first
))
344 if(first
[i
] == _T('\"'))
345 memmove(&first
[i
],&first
[i
+ 1], _tcslen(&first
[i
]) * sizeof(TCHAR
));
349 /* Drop quotes around it just in case there is a space */
350 _tcscpy(full
,_T("\""));
352 _tcscat(full
,_T("\" "));
356 /* check for a drive change */
357 if ((_istalpha (first
[0])) && (!_tcscmp (first
+ 1, _T(":"))))
360 if (!SetCurrentDirectory(first
))
361 /* Guess they changed disc or something, handle that gracefully and get to root */
368 working
= SetCurrentDirectory(str
);
371 if (!working
) ConErrResPuts (STRING_FREE_ERROR1
);
376 /* get the PATH environment variable and parse it */
377 /* search the PATH environment variable for the binary */
378 if (!SearchForExecutable (first
, szFullName
))
380 error_bad_command ();
385 GetConsoleTitle (szWindowTitle
, MAX_PATH
);
388 /* check if this is a .BAT or .CMD file */
389 if (!_tcsicmp (_tcsrchr (szFullName
, _T('.')), _T(".bat")) ||
390 !_tcsicmp (_tcsrchr (szFullName
, _T('.')), _T(".cmd")))
393 DebugPrintf (_T("[BATCH: %s %s]\n"), szFullName
, rest
);
395 Batch (szFullName
, first
, rest
);
399 /* exec the program */
400 PROCESS_INFORMATION prci
;
404 DebugPrintf (_T("[EXEC: %s %s]\n"), full
, rest
);
406 /* build command line for CreateProcess() */
408 /* fill startup info */
409 memset (&stui
, 0, sizeof (STARTUPINFO
));
410 stui
.cb
= sizeof (STARTUPINFO
);
411 stui
.dwFlags
= STARTF_USESHOWWINDOW
;
412 stui
.wShowWindow
= SW_SHOWDEFAULT
;
414 // return console to standard mode
415 SetConsoleMode (GetStdHandle(STD_INPUT_HANDLE
),
416 ENABLE_LINE_INPUT
| ENABLE_PROCESSED_INPUT
| ENABLE_ECHO_INPUT
);
418 if (CreateProcess (szFullName
,
423 CREATE_NEW_PROCESS_GROUP
,
429 if (IsConsoleProcess(prci
.hProcess
))
431 /* FIXME: Protect this with critical section */
432 bChildProcessRunning
= TRUE
;
433 dwChildProcessId
= prci
.dwProcessId
;
435 WaitForSingleObject (prci
.hProcess
, INFINITE
);
437 /* FIXME: Protect this with critical section */
438 bChildProcessRunning
= FALSE
;
440 GetExitCodeProcess (prci
.hProcess
, &dwExitCode
);
441 nErrorLevel
= (INT
)dwExitCode
;
443 CloseHandle (prci
.hThread
);
444 CloseHandle (prci
.hProcess
);
449 DebugPrintf (_T("[ShellExecute: %s]\n"), full
);
451 // See if we can run this with ShellExecute() ie myfile.xls
455 DebugPrintf (_T("[ShellExecute failed!: %s]\n"), full
);
457 error_bad_command ();
460 // restore console mode
461 SetConsoleMode( GetStdHandle( STD_INPUT_HANDLE
),
462 ENABLE_PROCESSED_INPUT
);
465 /* Get code page if it has been change */
466 InputCodePage
= GetConsoleCP();
467 OutputCodePage
= GetConsoleOutputCP();
469 SetConsoleTitle (szWindowTitle
);
475 * look through the internal commands and determine whether or not this
476 * command is one of them. If it is, call the command. If not, call
477 * execute to run it as an external program.
479 * line - the command line of the program to run
484 DoCommand (LPTSTR line
)
486 TCHAR com
[CMDLINE_LENGTH
]; /* the first word in the command */
489 LPTSTR rest
; /* pointer to the rest of the command line */
494 DebugPrintf (_T("DoCommand: (\'%s\')\n"), line
);
497 /* Skip over initial white space */
498 while (_istspace (*line
))
504 /* Anything to do ? */
507 if (*rest
== _T('"'))
509 /* treat quoted words specially */
513 while(*rest
!= _T('\0') && *rest
!= _T('"'))
514 *cp
++ = _totlower (*rest
++);
515 if (*rest
== _T('"'))
520 while (!IsDelimiter (*rest
))
521 *cp
++ = _totlower (*rest
++);
525 /* Terminate first word */
528 /* commands are limited to MAX_PATH */
529 if(_tcslen(com
) > MAX_PATH
)
535 /* Skip over whitespace to rest of line */
536 while (_istspace (*rest
))
539 /* Scan internal command table */
540 for (cmdptr
= cmds
;; cmdptr
++)
542 /* If end of table execute ext cmd */
543 if (cmdptr
->name
== NULL
)
545 Execute (line
, com
, rest
);
549 if (!_tcscmp (com
, cmdptr
->name
))
551 cmdptr
->func (com
, rest
);
555 /* The following code handles the case of commands like CD which
556 * are recognised even when the command name and parameter are
557 * not space separated.
563 /* Get length of command name */
564 cl
= _tcslen (cmdptr
->name
);
566 if ((cmdptr
->flags
& CMD_SPECIAL
) &&
567 (!_tcsncmp (cmdptr
->name
, com
, cl
)) &&
568 (_tcschr (_T("\\.-"), *(com
+ cl
))))
570 /* OK its one of the specials...*/
572 /* Terminate first word properly */
575 /* Call with new rest */
576 cmdptr
->func (com
, cstart
+ cl
);
585 * process the command line and execute the appropriate functions
586 * full input/output redirection and piping are supported
589 VOID
ParseCommandLine (LPTSTR cmd
)
591 TCHAR szMsg
[RC_STRING_MAX_SIZE
];
592 TCHAR cmdline
[CMDLINE_LENGTH
];
594 #ifdef FEATURE_REDIRECTION
595 TCHAR in
[CMDLINE_LENGTH
] = _T("");
596 TCHAR out
[CMDLINE_LENGTH
] = _T("");
597 TCHAR err
[CMDLINE_LENGTH
] = _T("");
598 TCHAR szTempPath
[MAX_PATH
] = _T(".\\");
599 TCHAR szFileName
[2][MAX_PATH
] = {_T(""), _T("")};
600 HANDLE hFile
[2] = {INVALID_HANDLE_VALUE
, INVALID_HANDLE_VALUE
};
606 BOOL bNewBatch
= TRUE
;
610 #endif /* FEATURE_REDIRECTION */
612 _tcscpy (cmdline
, cmd
);
616 DebugPrintf (_T("ParseCommandLine: (\'%s\')\n"), s
);
619 #ifdef FEATURE_ALIASES
620 /* expand all aliases */
621 ExpandAlias (s
, CMDLINE_LENGTH
);
622 #endif /* FEATURE_ALIAS */
624 #ifdef FEATURE_REDIRECTION
625 /* find the temp path to store temporary files */
626 Length
= GetTempPath (MAX_PATH
, szTempPath
);
627 if (Length
> 0 && Length
< MAX_PATH
)
629 Attributes
= GetFileAttributes(szTempPath
);
630 if (Attributes
== 0xffffffff ||
631 !(Attributes
& FILE_ATTRIBUTE_DIRECTORY
))
636 if (Length
== 0 || Length
>= MAX_PATH
)
638 _tcscpy(szTempPath
, _T(".\\"));
640 if (szTempPath
[_tcslen (szTempPath
) - 1] != _T('\\'))
641 _tcscat (szTempPath
, _T("\\"));
643 /* get the redirections from the command line */
644 num
= GetRedirection (s
, in
, out
, err
, &nRedirFlags
);
646 /* more efficient, but do we really need to do this? */
647 for (t
= in
; _istspace (*t
); t
++)
651 for (t
= out
; _istspace (*t
); t
++)
655 for (t
= err
; _istspace (*t
); t
++)
659 if(bc
&& !_tcslen (in
) && _tcslen (bc
->In
))
661 if(bc
&& !out
[0] && _tcslen(bc
->Out
))
663 nRedirFlags
|= OUTPUT_APPEND
;
664 _tcscpy(out
, bc
->Out
);
666 if(bc
&& !_tcslen (err
) && _tcslen (bc
->Err
))
668 nRedirFlags
|= ERROR_APPEND
;
669 _tcscpy(err
, bc
->Err
);
673 /* Set up the initial conditions ... */
674 /* preserve STDIN, STDOUT and STDERR handles */
675 hOldConIn
= GetStdHandle (STD_INPUT_HANDLE
);
676 hOldConOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
677 hOldConErr
= GetStdHandle (STD_ERROR_HANDLE
);
683 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
685 /* we need make sure the LastError msg is zero before calling CreateFile */
688 /* Set up pipe for the standard input handler */
689 hFile
= CreateFile (in
, GENERIC_READ
, FILE_SHARE_READ
, &sa
, OPEN_EXISTING
,
690 FILE_ATTRIBUTE_NORMAL
, NULL
);
691 if (hFile
== INVALID_HANDLE_VALUE
)
693 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR1
, szMsg
, RC_STRING_MAX_SIZE
);
694 ConErrPrintf(szMsg
, in
);
698 if (!SetStdHandle (STD_INPUT_HANDLE
, hFile
))
700 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR1
, szMsg
, RC_STRING_MAX_SIZE
);
701 ConErrPrintf(szMsg
, in
);
705 DebugPrintf (_T("Input redirected from: %s\n"), in
);
709 /* Now do all but the last pipe command */
710 *szFileName
[0] = _T('\0');
711 hFile
[0] = INVALID_HANDLE_VALUE
;
715 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
717 /* Create unique temporary file name */
718 GetTempFileName (szTempPath
, _T("CMD"), 0, szFileName
[1]);
720 /* we need make sure the LastError msg is zero before calling CreateFile */
723 /* Set current stdout to temporary file */
724 hFile
[1] = CreateFile (szFileName
[1], GENERIC_WRITE
, 0, &sa
,
725 TRUNCATE_EXISTING
, FILE_ATTRIBUTE_TEMPORARY
, NULL
);
727 if (hFile
[1] == INVALID_HANDLE_VALUE
)
729 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR2
, szMsg
, RC_STRING_MAX_SIZE
);
734 SetStdHandle (STD_OUTPUT_HANDLE
, hFile
[1]);
738 /* close stdout file */
739 SetStdHandle (STD_OUTPUT_HANDLE
, hOldConOut
);
740 if ((hFile
[1] != INVALID_HANDLE_VALUE
) && (hFile
[1] != hOldConOut
))
742 CloseHandle (hFile
[1]);
743 hFile
[1] = INVALID_HANDLE_VALUE
;
746 /* close old stdin file */
747 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
748 if ((hFile
[0] != INVALID_HANDLE_VALUE
) && (hFile
[0] != hOldConIn
))
750 /* delete old stdin file, if it is a real file */
751 CloseHandle (hFile
[0]);
752 hFile
[0] = INVALID_HANDLE_VALUE
;
753 DeleteFile (szFileName
[0]);
754 *szFileName
[0] = _T('\0');
757 /* copy stdout file name to stdin file name */
758 _tcscpy (szFileName
[0], szFileName
[1]);
759 *szFileName
[1] = _T('\0');
761 /* we need make sure the LastError msg is zero before calling CreateFile */
764 /* open new stdin file */
765 hFile
[0] = CreateFile (szFileName
[0], GENERIC_READ
, 0, &sa
,
766 OPEN_EXISTING
, FILE_ATTRIBUTE_TEMPORARY
, NULL
);
767 SetStdHandle (STD_INPUT_HANDLE
, hFile
[0]);
769 s
= s
+ _tcslen (s
) + 1;
772 /* Now set up the end conditions... */
773 /* redirect STDOUT */
776 /* Final output to here */
778 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
780 /* we need make sure the LastError msg is zero before calling CreateFile */
783 hFile
= CreateFile (out
, GENERIC_WRITE
, FILE_SHARE_WRITE
| FILE_SHARE_READ
| FILE_SHARE_DELETE
, &sa
,
784 (nRedirFlags
& OUTPUT_APPEND
) ? OPEN_ALWAYS
: CREATE_ALWAYS
,
785 FILE_ATTRIBUTE_NORMAL
| FILE_FLAG_WRITE_THROUGH
, NULL
);
787 if (hFile
== INVALID_HANDLE_VALUE
)
789 INT size
= _tcslen(out
)-1;
791 if (out
[size
] != _T(':'))
793 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR3
, szMsg
, RC_STRING_MAX_SIZE
);
794 ConErrPrintf(szMsg
, out
);
799 hFile
= CreateFile (out
, GENERIC_WRITE
, FILE_SHARE_WRITE
| FILE_SHARE_READ
| FILE_SHARE_DELETE
, &sa
,
800 (nRedirFlags
& OUTPUT_APPEND
) ? OPEN_ALWAYS
: CREATE_ALWAYS
,
801 FILE_ATTRIBUTE_NORMAL
| FILE_FLAG_WRITE_THROUGH
, NULL
);
803 if (hFile
== INVALID_HANDLE_VALUE
)
805 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR3
, szMsg
, RC_STRING_MAX_SIZE
);
806 ConErrPrintf(szMsg
, out
);
812 if (!SetStdHandle (STD_OUTPUT_HANDLE
, hFile
))
814 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR3
, szMsg
, RC_STRING_MAX_SIZE
);
815 ConErrPrintf(szMsg
, out
);
819 if (nRedirFlags
& OUTPUT_APPEND
)
823 if (GetFileType (hFile
) == FILE_TYPE_DISK
)
824 SetFilePointer (hFile
, 0, &lHighPos
, FILE_END
);
827 DebugPrintf (_T("Output redirected to: %s\n"), out
);
830 else if (hOldConOut
!= INVALID_HANDLE_VALUE
)
832 /* Restore original stdout */
833 HANDLE hOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
834 SetStdHandle (STD_OUTPUT_HANDLE
, hOldConOut
);
835 if (hOldConOut
!= hOut
)
837 hOldConOut
= INVALID_HANDLE_VALUE
;
840 /* redirect STDERR */
843 /* Final output to here */
845 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
847 if (!_tcscmp (err
, out
))
850 DebugPrintf (_T("Stdout and stderr will use the same file!!\n"));
852 DuplicateHandle (GetCurrentProcess (),
853 GetStdHandle (STD_OUTPUT_HANDLE
),
854 GetCurrentProcess (),
855 &hFile
, 0, TRUE
, DUPLICATE_SAME_ACCESS
);
859 hFile
= CreateFile (err
,
861 FILE_SHARE_WRITE
| FILE_SHARE_READ
| FILE_SHARE_DELETE
,
863 (nRedirFlags
& ERROR_APPEND
) ? OPEN_ALWAYS
: CREATE_ALWAYS
,
864 FILE_ATTRIBUTE_NORMAL
| FILE_FLAG_WRITE_THROUGH
,
866 if (hFile
== INVALID_HANDLE_VALUE
)
868 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR3
, szMsg
, RC_STRING_MAX_SIZE
);
869 ConErrPrintf(szMsg
, err
);
874 if (!SetStdHandle (STD_ERROR_HANDLE
, hFile
))
876 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR3
, szMsg
, RC_STRING_MAX_SIZE
);
877 ConErrPrintf(szMsg
, err
);
881 if (nRedirFlags
& ERROR_APPEND
)
885 if (GetFileType (hFile
) == FILE_TYPE_DISK
)
886 SetFilePointer (hFile
, 0, &lHighPos
, FILE_END
);
889 DebugPrintf (_T("Error redirected to: %s\n"), err
);
892 else if (hOldConErr
!= INVALID_HANDLE_VALUE
)
894 /* Restore original stderr */
895 HANDLE hErr
= GetStdHandle (STD_ERROR_HANDLE
);
896 SetStdHandle (STD_ERROR_HANDLE
, hOldConErr
);
897 if (hOldConErr
!= hErr
)
899 hOldConErr
= INVALID_HANDLE_VALUE
;
906 /* process final command */
909 #ifdef FEATURE_REDIRECTION
911 AddBatchRedirection(in
, out
, err
);
912 /* close old stdin file */
913 #if 0 /* buggy implementation */
914 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
915 if ((hFile
[0] != INVALID_HANDLE_VALUE
) &&
916 (hFile
[0] != hOldConIn
))
918 /* delete old stdin file, if it is a real file */
919 CloseHandle (hFile
[0]);
920 hFile
[0] = INVALID_HANDLE_VALUE
;
921 DeleteFile (szFileName
[0]);
922 *szFileName
[0] = _T('\0');
925 /* Restore original STDIN */
926 if (hOldConIn
!= INVALID_HANDLE_VALUE
)
928 HANDLE hIn
= GetStdHandle (STD_INPUT_HANDLE
);
929 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
930 if (hOldConIn
!= hIn
)
932 hOldConIn
= INVALID_HANDLE_VALUE
;
937 DebugPrintf (_T("Can't restore STDIN! Is invalid!!\n"), out
);
940 #endif /* buggy implementation */
943 if (hOldConIn
!= INVALID_HANDLE_VALUE
)
945 HANDLE hIn
= GetStdHandle (STD_INPUT_HANDLE
);
946 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
947 if (hIn
== INVALID_HANDLE_VALUE
)
950 DebugPrintf (_T("Previous STDIN is invalid!!\n"));
955 if (GetFileType (hIn
) == FILE_TYPE_DISK
)
959 CloseHandle (hFile
[0]);
960 hFile
[0] = INVALID_HANDLE_VALUE
;
961 DeleteFile (szFileName
[0]);
962 *szFileName
[0] = _T('\0');
967 DebugPrintf (_T("hFile[0] and hIn dont match!!!\n"));
975 /* Restore original STDOUT */
976 if (hOldConOut
!= INVALID_HANDLE_VALUE
)
978 HANDLE hOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
979 SetStdHandle (STD_OUTPUT_HANDLE
, hOldConOut
);
980 if (hOldConOut
!= hOut
)
982 hOldConOut
= INVALID_HANDLE_VALUE
;
985 /* Restore original STDERR */
986 if (hOldConErr
!= INVALID_HANDLE_VALUE
)
988 HANDLE hErr
= GetStdHandle (STD_ERROR_HANDLE
);
989 SetStdHandle (STD_ERROR_HANDLE
, hOldConErr
);
990 if (hOldConErr
!= hErr
)
992 hOldConErr
= INVALID_HANDLE_VALUE
;
994 #endif /* FEATURE_REDIRECTION */
999 * do the prompt/input/process loop
1004 ProcessInput (BOOL bFlag
)
1006 TCHAR commandline
[CMDLINE_LENGTH
];
1007 TCHAR readline
[CMDLINE_LENGTH
];
1016 /* if no batch input then... */
1017 if (!(ip
= ReadBatchLine (&bEchoThisLine
)))
1022 ReadCommand (readline
, CMDLINE_LENGTH
);
1024 bEchoThisLine
= FALSE
;
1048 if ((tp
= FindArg (*ip
- _T('0'))))
1050 cp
= _stpcpy (cp
, tp
);
1058 cp
+= _stprintf (cp
, _T("%u"), nErrorLevel
);
1063 tp
= _tcschr(ip
, _T('%'));
1065 (tp
<= _tcschr(ip
, _T(' ')) - 1))
1071 /* FIXME: Correct error handling when it can not alloc memmory */
1074 if (_tcsicmp(ip
,_T("cd")) ==0)
1076 TCHAR szPath
[MAX_PATH
];
1077 GetCurrentDirectory (MAX_PATH
, szPath
);
1078 cp
= _stpcpy (cp
, szPath
);
1081 else if (_tcsicmp(ip
,_T("time")) ==0)
1087 _sntprintf(szTime
,40,_T("%02d%c%02d%c%02d%c%02d"), t
.wHour
, cTimeSeparator
,t
.wMinute
, cTimeSeparator
,t
.wSecond
, cDecimalSeparator
, t
.wMilliseconds
);
1088 cp
= _stpcpy (cp
, szTime
);
1092 else if (_tcsicmp(ip
,_T("date")) ==0)
1096 GetDateFormat(LOCALE_USER_DEFAULT
, 0, NULL
, _T("ddd"), szDate
, sizeof (szDate
));
1097 cp
= _stpcpy (cp
, szDate
);
1098 cp
= _stpcpy (cp
, _T(" "));
1099 GetDateFormat(LOCALE_USER_DEFAULT
, DATE_SHORTDATE
, NULL
, NULL
, szDate
, sizeof (szDate
));
1100 cp
= _stpcpy (cp
, szDate
);
1104 else if (_tcsicmp(ip
,_T("random")) ==0)
1107 /* Get random number */
1108 _itot(rand(),szRand
,10);
1109 cp
= _stpcpy (cp
, szRand
);
1113 else if (_tcsicmp(ip
,_T("cmdcmdline")) ==0)
1116 /* Get random number */
1117 pargv
= GetCommandLine();
1118 cp
= _stpcpy (cp
, pargv
);
1121 /* %CMDEXTVERSION% */
1122 else if (_tcsicmp(ip
,_T("cmdextversion")) ==0)
1125 /* Set version number to 2 */
1127 cp
= _stpcpy (cp
, szVER
);
1131 else if (_tcsicmp(ip
,_T("errorlevel")) ==0)
1133 evar
= malloc ( size
* sizeof(TCHAR
));
1137 memset(evar
,0,512 * sizeof(TCHAR
));
1138 _itot(nErrorLevel
,evar
,10);
1139 cp
= _stpcpy (cp
, evar
);
1145 evar
= malloc ( 512 * sizeof(TCHAR
));
1149 size
= GetEnvironmentVariable (ip
, evar
, 512);
1150 if(GetLastError() == ERROR_ENVVAR_NOT_FOUND
)
1152 /* if no env var is found you must
1153 continue with what was input*/
1154 cp
= _stpcpy (cp
, _T("%"));
1155 cp
= _stpcpy (cp
, ip
);
1156 cp
= _stpcpy (cp
, _T("%"));
1162 evar
= realloc(evar
,size
* sizeof(TCHAR
) );
1167 size
= GetEnvironmentVariable (ip
, evar
, size
);
1172 cp
= _stpcpy (cp
, evar
);
1195 if (_istcntrl (*ip
))
1202 /* strip trailing spaces */
1203 while ((--cp
>= commandline
) && _istspace (*cp
));
1205 *(cp
+ 1) = _T('\0');
1208 /* Echo batch file line */
1212 ConOutPuts (commandline
);
1217 ParseCommandLine (commandline
);
1218 if (bEcho
&& !bIgnoreEcho
)
1220 bIgnoreEcho
= FALSE
;
1223 while (!bCanExit
|| !bExit
);
1230 * control-break handler.
1232 BOOL WINAPI
BreakHandler (DWORD dwCtrlType
)
1235 if ((dwCtrlType
!= CTRL_C_EVENT
) &&
1236 (dwCtrlType
!= CTRL_BREAK_EVENT
))
1239 if (bChildProcessRunning
== TRUE
)
1241 GenerateConsoleCtrlEvent (CTRL_C_EVENT
,
1246 /* FIXME: Handle batch files */
1248 /* FIXME: Print "^C" */
1255 VOID
AddBreakHandler (VOID
)
1257 SetConsoleCtrlHandler ((PHANDLER_ROUTINE
)BreakHandler
, TRUE
);
1261 VOID
RemoveBreakHandler (VOID
)
1263 SetConsoleCtrlHandler ((PHANDLER_ROUTINE
)BreakHandler
, FALSE
);
1268 * show commands and options that are available.
1275 /* print command list */
1276 ConOutResPuts(STRING_CMD_HELP1
);
1279 /* print feature list */
1280 ConOutResPuts(STRING_CMD_HELP2
);
1282 #ifdef FEATURE_ALIASES
1283 ConOutResPuts(STRING_CMD_HELP3
);
1285 #ifdef FEATURE_HISTORY
1286 ConOutResPuts(STRING_CMD_HELP4
);
1288 #ifdef FEATURE_UNIX_FILENAME_COMPLETION
1289 ConOutResPuts(STRING_CMD_HELP5
);
1291 #ifdef FEATURE_DIRECTORY_STACK
1292 ConOutResPuts(STRING_CMD_HELP6
);
1294 #ifdef FEATURE_REDIRECTION
1295 ConOutResPuts(STRING_CMD_HELP7
);
1297 ConOutChar(_T('\n'));
1302 * set up global initializations and process parameters
1304 * argc - number of parameters to command.com
1305 * argv - command-line parameters
1309 Initialize (int argc
, TCHAR
* argv
[])
1311 TCHAR commandline
[CMDLINE_LENGTH
];
1312 TCHAR ModuleName
[_MAX_PATH
+ 1];
1316 //TCHAR *ptr, *cmdLine;
1318 /* get version information */
1319 osvi
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
1320 GetVersionEx (&osvi
);
1322 /* Some people like to run ReactOS cmd.exe on Win98, it helps in the
1323 build process. So don't link implicitly against ntdll.dll, load it
1324 dynamically instead */
1326 if (osvi
.dwPlatformId
== VER_PLATFORM_WIN32_NT
)
1328 /* ntdll is always present on NT */
1329 NtDllModule
= GetModuleHandle(TEXT("ntdll.dll"));
1333 /* not all 9x versions have a ntdll.dll, try to load it */
1334 NtDllModule
= LoadLibrary(TEXT("ntdll.dll"));
1337 if (NtDllModule
!= NULL
)
1339 NtQueryInformationProcessPtr
= (NtQueryInformationProcessProc
)GetProcAddress(NtDllModule
, "NtQueryInformationProcess");
1340 NtReadVirtualMemoryPtr
= (NtReadVirtualMemoryProc
)GetProcAddress(NtDllModule
, "NtReadVirtualMemory");
1347 DebugPrintf (_T("[command args:\n"));
1348 for (x
= 0; x
< argc
; x
++)
1350 DebugPrintf (_T("%d. %s\n"), x
, argv
[x
]);
1352 DebugPrintf (_T("]\n"));
1357 /* get default input and output console handles */
1358 hOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
1359 hIn
= GetStdHandle (STD_INPUT_HANDLE
);
1361 SetEnvironmentVariable (_T("PROMPT"), _T("$P$G"));
1364 if (argc
>= 2 && !_tcsncmp (argv
[1], _T("/?"), 2))
1366 ConOutResPaging(TRUE
,STRING_CMD_HELP8
);
1369 SetConsoleMode (hIn
, ENABLE_PROCESSED_INPUT
);
1371 #ifdef INCLUDE_CMD_CHDIR
1375 #ifdef FATURE_ALIASES
1381 for (i
= 1; i
< argc
; i
++)
1383 if (!_tcsicmp (argv
[i
], _T("/p")))
1385 if (!IsExistingFile (_T("\\autoexec.bat")))
1387 #ifdef INCLUDE_CMD_DATE
1388 cmd_date (_T(""), _T(""));
1390 #ifdef INCLUDE_CMD_TIME
1391 cmd_time (_T(""), _T(""));
1396 ParseCommandLine (_T("\\autoexec.bat"));
1400 else if (!_tcsicmp (argv
[i
], _T("/c")))
1402 /* This just runs a program and exits */
1406 _tcscpy (commandline
, argv
[i
]);
1409 _tcscat (commandline
, _T(" "));
1410 _tcscat (commandline
, argv
[i
]);
1413 ParseCommandLine(commandline
);
1414 ExitProcess (ProcessInput (TRUE
));
1421 else if (!_tcsicmp (argv
[i
], _T("/k")))
1423 /* This just runs a program and remains */
1427 _tcscpy (commandline
, argv
[i
]);
1430 _tcscat (commandline
, _T(" "));
1431 _tcscat (commandline
, argv
[i
]);
1434 ParseCommandLine(commandline
);
1437 #ifdef INCLUDE_CMD_COLOR
1438 else if (!_tcsnicmp (argv
[i
], _T("/t:"), 3))
1440 /* process /t (color) argument */
1441 wDefColor
= (WORD
)_tcstoul (&argv
[i
][3], NULL
, 16);
1443 SetScreenColor (wColor
, TRUE
);
1449 /* run cmdstart.bat */
1450 if (IsExistingFile (_T("cmdstart.bat")))
1452 ParseCommandLine (_T("cmdstart.bat"));
1454 else if (IsExistingFile (_T("\\cmdstart.bat")))
1456 ParseCommandLine (_T("\\cmdstart.bat"));
1461 /* try to run cmdstart.bat from install dir */
1464 _tcscpy (commandline
, argv
[0]);
1465 p
= _tcsrchr (commandline
, _T('\\')) + 1;
1466 _tcscpy (p
, _T("cmdstart.bat"));
1468 if (IsExistingFile (_T("commandline")))
1470 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR4
, szMsg
, RC_STRING_MAX_SIZE
);
1471 ConErrPrintf(szMsg
, commandline
);
1472 ParseCommandLine (commandline
);
1477 #ifdef FEATURE_DIR_STACK
1478 /* initialize directory stack */
1479 InitDirectoryStack ();
1483 #ifdef FEATURE_HISTORY
1484 /*initialize history*/
1488 /* Set COMSPEC environment variable */
1489 if (0 != GetModuleFileName (NULL
, ModuleName
, _MAX_PATH
+ 1))
1491 ModuleName
[_MAX_PATH
] = _T('\0');
1492 SetEnvironmentVariable (_T("COMSPEC"), ModuleName
);
1495 /* add ctrl break handler */
1500 static VOID
Cleanup (int argc
, TCHAR
*argv
[])
1503 TCHAR szMsg
[RC_STRING_MAX_SIZE
];
1506 /* run cmdexit.bat */
1507 if (IsExistingFile (_T("cmdexit.bat")))
1509 ConErrResPuts(STRING_CMD_ERROR5
);
1511 ParseCommandLine (_T("cmdexit.bat"));
1513 else if (IsExistingFile (_T("\\cmdexit.bat")))
1515 ConErrResPuts (STRING_CMD_ERROR5
);
1516 ParseCommandLine (_T("\\cmdexit.bat"));
1521 /* try to run cmdexit.bat from install dir */
1522 TCHAR commandline
[CMDLINE_LENGTH
];
1525 _tcscpy (commandline
, argv
[0]);
1526 p
= _tcsrchr (commandline
, _T('\\')) + 1;
1527 _tcscpy (p
, _T("cmdexit.bat"));
1529 if (IsExistingFile (_T("commandline")))
1531 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR4
, szMsg
, RC_STRING_MAX_SIZE
);
1532 ConErrPrintf(szMsg
, commandline
);
1533 ParseCommandLine (commandline
);
1538 #ifdef FEATURE_ALIASES
1542 #ifdef FEATURE_DIECTORY_STACK
1543 /* destroy directory stack */
1544 DestroyDirectoryStack ();
1547 #ifdef INCLUDE_CMD_CHDIR
1551 #ifdef FEATURE_HISTORY
1556 /* remove ctrl break handler */
1557 RemoveBreakHandler ();
1558 SetConsoleMode( GetStdHandle( STD_INPUT_HANDLE
),
1559 ENABLE_LINE_INPUT
| ENABLE_PROCESSED_INPUT
| ENABLE_ECHO_INPUT
);
1561 if (NtDllModule
!= NULL
)
1563 FreeLibrary(NtDllModule
);
1569 PWCHAR
* _CommandLineToArgvW(PWCHAR lpCmdLine
, int *pNumArgs
)
1571 PWCHAR
* argvw
= NULL
;
1572 PWCHAR ptr
= lpCmdLine
;
1579 while(lpCmdLine
&& *lpCmdLine
)
1581 while (iswspace(*lpCmdLine
)) lpCmdLine
++;
1584 if ((NumArgs
% 10)==0)
1586 PWCHAR
* old_argvw
= argvw
;
1587 argvw
= malloc((NumArgs
+ 10) * sizeof(PWCHAR
));
1588 memcpy(argvw
, old_argvw
, NumArgs
* sizeof(PWCHAR
));
1591 ptr
= wcschr(lpCmdLine
, L
' ');
1594 len
= ptr
- lpCmdLine
;
1598 len
= wcslen(lpCmdLine
);
1600 str
= malloc((len
+ 1) * sizeof(WCHAR
));
1601 memcpy(str
, lpCmdLine
, len
* sizeof(WCHAR
));
1608 *pNumArgs
= NumArgs
;
1620 int _main (int argc
, char *argv
[])
1623 TCHAR startPath
[MAX_PATH
];
1624 CONSOLE_SCREEN_BUFFER_INFO Info
;
1630 argv
= _CommandLineToArgvW(GetCommandLineW(), &argc
);
1632 argv
= CommandLineToArgvW(GetCommandLineW(), &argc
);
1636 GetCurrentDirectory(MAX_PATH
,startPath
);
1643 hConsole
= CreateFile(_T("CONOUT$"), GENERIC_READ
|GENERIC_WRITE
,
1644 FILE_SHARE_READ
|FILE_SHARE_WRITE
, NULL
,
1645 OPEN_EXISTING
, 0, NULL
);
1646 if (GetConsoleScreenBufferInfo(hConsole
, &Info
) == FALSE
)
1648 ConErrFormatMessage(GetLastError());
1651 wColor
= Info
.wAttributes
;
1654 InputCodePage
= GetConsoleCP();
1655 OutputCodePage
= GetConsoleOutputCP();
1656 CMD_ModuleHandle
= GetModuleHandle(NULL
);
1658 /* check switches on command-line */
1659 Initialize(argc
, argv
);
1661 /* call prompt routine */
1662 nExitCode
= ProcessInput(FALSE
);
1665 /* do the cleanup */
1666 Cleanup(argc
, argv
);