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
;
168 static NtQueryInformationProcessProc NtQueryInformationProcessPtr
;
169 static NtReadVirtualMemoryProc NtReadVirtualMemoryPtr
;
170 static BOOL NtDllChecked
= FALSE
;
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
;
198 /* Some people like to run ReactOS cmd.exe on Win98, it helps in the
199 build process. So don't link implicitly against ntdll.dll, load it
200 dynamically instead */
204 NtDllModule
= LoadLibrary(_T("ntdll.dll"));
205 if (NULL
== NtDllModule
)
207 /* Probably non-WinNT system. Just wait for the commands
209 NtQueryInformationProcessPtr
= NULL
;
210 NtReadVirtualMemoryPtr
= NULL
;
213 NtQueryInformationProcessPtr
= (NtQueryInformationProcessProc
)
214 GetProcAddress(NtDllModule
, "NtQueryInformationProcess");
215 NtReadVirtualMemoryPtr
= (NtReadVirtualMemoryProc
)
216 GetProcAddress(NtDllModule
, "NtReadVirtualMemory");
219 if (NULL
== NtQueryInformationProcessPtr
|| NULL
== NtReadVirtualMemoryPtr
)
224 Status
= NtQueryInformationProcessPtr(Process
, ProcessBasicInformation
,
225 &Info
, sizeof(PROCESS_BASIC_INFORMATION
), NULL
);
226 if (! NT_SUCCESS(Status
))
229 DebugPrintf (_T("NtQueryInformationProcess failed with status %08x\n"), Status
);
233 Status
= NtReadVirtualMemoryPtr(Process
, Info
.PebBaseAddress
, &ProcessPeb
,
234 sizeof(PEB
), &BytesRead
);
235 if (! NT_SUCCESS(Status
) || sizeof(PEB
) != BytesRead
)
238 DebugPrintf (_T("Couldn't read virt mem status %08x bytes read %lu\n"), Status
, BytesRead
);
243 return IMAGE_SUBSYSTEM_WINDOWS_CUI
== ProcessPeb
.ImageSubSystem
;
249 #define SHELLEXECUTETEXT "ShellExecuteW"
251 #define SHELLEXECUTETEXT "ShellExecuteA"
254 typedef HINSTANCE (WINAPI
*MYEX
)(
258 LPCTSTR lpParameters
,
265 static BOOL
RunFile(LPTSTR filename
)
272 DebugPrintf (_T("RunFile(%s)\n"), filename
);
274 hShell32
= LoadLibrary(_T("SHELL32.DLL"));
278 DebugPrintf (_T("RunFile: couldn't load SHELL32.DLL!\n"));
283 hShExt
= (MYEX
)(FARPROC
)GetProcAddress(hShell32
, SHELLEXECUTETEXT
);
287 DebugPrintf (_T("RunFile: couldn't find ShellExecuteA/W in SHELL32.DLL!\n"));
289 FreeLibrary(hShell32
);
294 DebugPrintf (_T("RunFile: ShellExecuteA/W is at %x\n"), hShExt
);
297 ret
= (hShExt
)(NULL
, _T("open"), filename
, NULL
, NULL
, SW_SHOWNORMAL
);
300 DebugPrintf (_T("RunFile: ShellExecuteA/W returned %d\n"), (DWORD
)ret
);
303 FreeLibrary(hShell32
);
304 return (((DWORD
)ret
) > 32);
310 * This command (in first) was not found in the command table
312 * first - first word on command line
313 * rest - rest of command line
317 Execute (LPTSTR full
, LPTSTR first
, LPTSTR rest
)
319 TCHAR szFullName
[MAX_PATH
];
321 TCHAR szWindowTitle
[MAX_PATH
];
323 DWORD dwExitCode
= 0;
326 DebugPrintf (_T("Execute: \'%s\' \'%s\'\n"), first
, rest
);
329 /* check for a drive change */
330 if ((_istalpha (first
[0])) && (!_tcscmp (first
+ 1, _T(":"))))
333 if (!SetCurrentDirectory(first
))
334 /* Guess they changed disc or something, handle that gracefully and get to root */
341 working
= SetCurrentDirectory(str
);
344 if (!working
) ConErrResPuts (STRING_FREE_ERROR1
);
349 /* get the PATH environment variable and parse it */
350 /* search the PATH environment variable for the binary */
351 if (!SearchForExecutable (first
, szFullName
))
353 error_bad_command ();
358 GetConsoleTitle (szWindowTitle
, MAX_PATH
);
361 /* check if this is a .BAT or .CMD file */
362 if (!_tcsicmp (_tcsrchr (szFullName
, _T('.')), _T(".bat")) ||
363 !_tcsicmp (_tcsrchr (szFullName
, _T('.')), _T(".cmd")))
366 DebugPrintf (_T("[BATCH: %s %s]\n"), szFullName
, rest
);
368 Batch (szFullName
, first
, rest
);
372 /* exec the program */
373 PROCESS_INFORMATION prci
;
377 DebugPrintf (_T("[EXEC: %s %s]\n"), full
, rest
);
379 /* build command line for CreateProcess() */
381 /* fill startup info */
382 memset (&stui
, 0, sizeof (STARTUPINFO
));
383 stui
.cb
= sizeof (STARTUPINFO
);
384 stui
.dwFlags
= STARTF_USESHOWWINDOW
;
385 stui
.wShowWindow
= SW_SHOWDEFAULT
;
387 // return console to standard mode
388 SetConsoleMode (GetStdHandle(STD_INPUT_HANDLE
),
389 ENABLE_LINE_INPUT
| ENABLE_PROCESSED_INPUT
| ENABLE_ECHO_INPUT
);
391 if (CreateProcess (szFullName
,
396 CREATE_NEW_PROCESS_GROUP
,
402 if (IsConsoleProcess(prci
.hProcess
))
404 /* FIXME: Protect this with critical section */
405 bChildProcessRunning
= TRUE
;
406 dwChildProcessId
= prci
.dwProcessId
;
408 WaitForSingleObject (prci
.hProcess
, INFINITE
);
410 /* FIXME: Protect this with critical section */
411 bChildProcessRunning
= FALSE
;
413 GetExitCodeProcess (prci
.hProcess
, &dwExitCode
);
414 nErrorLevel
= (INT
)dwExitCode
;
416 CloseHandle (prci
.hThread
);
417 CloseHandle (prci
.hProcess
);
422 DebugPrintf (_T("[ShellExecute: %s]\n"), full
);
424 // See if we can run this with ShellExecute() ie myfile.xls
428 DebugPrintf (_T("[ShellExecute failed!: %s]\n"), full
);
430 error_bad_command ();
433 // restore console mode
434 SetConsoleMode( GetStdHandle( STD_INPUT_HANDLE
),
435 ENABLE_PROCESSED_INPUT
);
438 /* Get code page if it has been change */
439 InputCodePage
= GetConsoleCP();
440 OutputCodePage
= GetConsoleOutputCP();
442 SetConsoleTitle (szWindowTitle
);
448 * look through the internal commands and determine whether or not this
449 * command is one of them. If it is, call the command. If not, call
450 * execute to run it as an external program.
452 * line - the command line of the program to run
457 DoCommand (LPTSTR line
)
459 TCHAR com
[CMDLINE_LENGTH
]; /* the first word in the command */
462 LPTSTR rest
; /* pointer to the rest of the command line */
467 DebugPrintf (_T("DoCommand: (\'%s\')\n"), line
);
470 /* Skip over initial white space */
471 while (_istspace (*line
))
477 /* Anything to do ? */
480 if (*rest
== _T('"'))
482 /* treat quoted words specially */
486 while(*rest
!= _T('\0') && *rest
!= _T('"'))
487 *cp
++ = _totlower (*rest
++);
488 if (*rest
== _T('"'))
493 while (!IsDelimiter (*rest
))
494 *cp
++ = _totlower (*rest
++);
498 /* Terminate first word */
501 /* commands are limited to MAX_PATH */
502 if(_tcslen(com
) > MAX_PATH
)
508 /* Skip over whitespace to rest of line */
509 while (_istspace (*rest
))
512 /* Scan internal command table */
513 for (cmdptr
= cmds
;; cmdptr
++)
515 /* If end of table execute ext cmd */
516 if (cmdptr
->name
== NULL
)
518 Execute (line
, com
, rest
);
522 if (!_tcscmp (com
, cmdptr
->name
))
524 cmdptr
->func (com
, rest
);
528 /* The following code handles the case of commands like CD which
529 * are recognised even when the command name and parameter are
530 * not space separated.
536 /* Get length of command name */
537 cl
= _tcslen (cmdptr
->name
);
539 if ((cmdptr
->flags
& CMD_SPECIAL
) &&
540 (!_tcsncmp (cmdptr
->name
, com
, cl
)) &&
541 (_tcschr (_T("\\.-"), *(com
+ cl
))))
543 /* OK its one of the specials...*/
545 /* Terminate first word properly */
548 /* Call with new rest */
549 cmdptr
->func (com
, cstart
+ cl
);
558 * process the command line and execute the appropriate functions
559 * full input/output redirection and piping are supported
562 VOID
ParseCommandLine (LPTSTR cmd
)
564 TCHAR szMsg
[RC_STRING_MAX_SIZE
];
565 TCHAR cmdline
[CMDLINE_LENGTH
];
567 #ifdef FEATURE_REDIRECTION
568 TCHAR in
[CMDLINE_LENGTH
] = _T("");
569 TCHAR out
[CMDLINE_LENGTH
] = _T("");
570 TCHAR err
[CMDLINE_LENGTH
] = _T("");
571 TCHAR szTempPath
[MAX_PATH
] = _T(".\\");
572 TCHAR szFileName
[2][MAX_PATH
] = {_T(""), _T("")};
573 HANDLE hFile
[2] = {INVALID_HANDLE_VALUE
, INVALID_HANDLE_VALUE
};
583 #endif /* FEATURE_REDIRECTION */
585 _tcscpy (cmdline
, cmd
);
589 DebugPrintf (_T("ParseCommandLine: (\'%s\')\n"), s
);
592 #ifdef FEATURE_ALIASES
593 /* expand all aliases */
594 ExpandAlias (s
, CMDLINE_LENGTH
);
595 #endif /* FEATURE_ALIAS */
597 #ifdef FEATURE_REDIRECTION
598 /* find the temp path to store temporary files */
599 Length
= GetTempPath (MAX_PATH
, szTempPath
);
600 if (Length
> 0 && Length
< MAX_PATH
)
602 Attributes
= GetFileAttributes(szTempPath
);
603 if (Attributes
== 0xffffffff ||
604 !(Attributes
& FILE_ATTRIBUTE_DIRECTORY
))
609 if (Length
== 0 || Length
>= MAX_PATH
)
611 _tcscpy(szTempPath
, _T(".\\"));
613 if (szTempPath
[_tcslen (szTempPath
) - 1] != _T('\\'))
614 _tcscat (szTempPath
, _T("\\"));
616 /* get the redirections from the command line */
617 num
= GetRedirection (s
, in
, out
, err
, &nRedirFlags
);
619 /* more efficient, but do we really need to do this? */
620 for (t
= in
; _istspace (*t
); t
++)
624 for (t
= out
; _istspace (*t
); t
++)
628 for (t
= err
; _istspace (*t
); t
++)
632 /* Set up the initial conditions ... */
633 /* preserve STDIN, STDOUT and STDERR handles */
634 hOldConIn
= GetStdHandle (STD_INPUT_HANDLE
);
635 hOldConOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
636 hOldConErr
= GetStdHandle (STD_ERROR_HANDLE
);
642 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
644 hFile
= CreateFile (in
, GENERIC_READ
, FILE_SHARE_READ
, &sa
, OPEN_EXISTING
,
645 FILE_ATTRIBUTE_NORMAL
, NULL
);
646 if (hFile
== INVALID_HANDLE_VALUE
)
648 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR1
, szMsg
, RC_STRING_MAX_SIZE
);
649 ConErrPrintf(szMsg
, in
);
653 if (!SetStdHandle (STD_INPUT_HANDLE
, hFile
))
655 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR1
, szMsg
, RC_STRING_MAX_SIZE
);
656 ConErrPrintf(szMsg
, in
);
660 DebugPrintf (_T("Input redirected from: %s\n"), in
);
664 /* Now do all but the last pipe command */
665 *szFileName
[0] = _T('\0');
666 hFile
[0] = INVALID_HANDLE_VALUE
;
670 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
672 /* Create unique temporary file name */
673 GetTempFileName (szTempPath
, _T("CMD"), 0, szFileName
[1]);
675 /* Set current stdout to temporary file */
676 hFile
[1] = CreateFile (szFileName
[1], GENERIC_WRITE
, 0, &sa
,
677 TRUNCATE_EXISTING
, FILE_ATTRIBUTE_TEMPORARY
, NULL
);
678 if (hFile
[1] == INVALID_HANDLE_VALUE
)
680 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR2
, szMsg
, RC_STRING_MAX_SIZE
);
685 SetStdHandle (STD_OUTPUT_HANDLE
, hFile
[1]);
689 /* close stdout file */
690 SetStdHandle (STD_OUTPUT_HANDLE
, hOldConOut
);
691 if ((hFile
[1] != INVALID_HANDLE_VALUE
) && (hFile
[1] != hOldConOut
))
693 CloseHandle (hFile
[1]);
694 hFile
[1] = INVALID_HANDLE_VALUE
;
697 /* close old stdin file */
698 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
699 if ((hFile
[0] != INVALID_HANDLE_VALUE
) && (hFile
[0] != hOldConIn
))
701 /* delete old stdin file, if it is a real file */
702 CloseHandle (hFile
[0]);
703 hFile
[0] = INVALID_HANDLE_VALUE
;
704 DeleteFile (szFileName
[0]);
705 *szFileName
[0] = _T('\0');
708 /* copy stdout file name to stdin file name */
709 _tcscpy (szFileName
[0], szFileName
[1]);
710 *szFileName
[1] = _T('\0');
712 /* open new stdin file */
713 hFile
[0] = CreateFile (szFileName
[0], GENERIC_READ
, 0, &sa
,
714 OPEN_EXISTING
, FILE_ATTRIBUTE_TEMPORARY
, NULL
);
715 SetStdHandle (STD_INPUT_HANDLE
, hFile
[0]);
717 s
= s
+ _tcslen (s
) + 1;
720 /* Now set up the end conditions... */
721 /* redirect STDOUT */
724 /* Final output to here */
726 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
728 hFile
= CreateFile (out
, GENERIC_WRITE
, FILE_SHARE_READ
, &sa
,
729 (nRedirFlags
& OUTPUT_APPEND
) ? OPEN_ALWAYS
: CREATE_ALWAYS
,
730 FILE_ATTRIBUTE_NORMAL
, NULL
);
731 if (hFile
== INVALID_HANDLE_VALUE
)
733 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR3
, szMsg
, RC_STRING_MAX_SIZE
);
734 ConErrPrintf(szMsg
, out
);
738 if (!SetStdHandle (STD_OUTPUT_HANDLE
, hFile
))
740 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR3
, szMsg
, RC_STRING_MAX_SIZE
);
741 ConErrPrintf(szMsg
, out
);
745 if (nRedirFlags
& OUTPUT_APPEND
)
749 if (GetFileType (hFile
) == FILE_TYPE_DISK
)
750 SetFilePointer (hFile
, 0, &lHighPos
, FILE_END
);
753 DebugPrintf (_T("Output redirected to: %s\n"), out
);
756 else if (hOldConOut
!= INVALID_HANDLE_VALUE
)
758 /* Restore original stdout */
759 HANDLE hOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
760 SetStdHandle (STD_OUTPUT_HANDLE
, hOldConOut
);
761 if (hOldConOut
!= hOut
)
763 hOldConOut
= INVALID_HANDLE_VALUE
;
766 /* redirect STDERR */
769 /* Final output to here */
771 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
773 if (!_tcscmp (err
, out
))
776 DebugPrintf (_T("Stdout and stderr will use the same file!!\n"));
778 DuplicateHandle (GetCurrentProcess (),
779 GetStdHandle (STD_OUTPUT_HANDLE
),
780 GetCurrentProcess (),
781 &hFile
, 0, TRUE
, DUPLICATE_SAME_ACCESS
);
785 hFile
= CreateFile (err
,
789 (nRedirFlags
& ERROR_APPEND
) ? OPEN_ALWAYS
: CREATE_ALWAYS
,
790 FILE_ATTRIBUTE_NORMAL
,
792 if (hFile
== INVALID_HANDLE_VALUE
)
794 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR3
, szMsg
, RC_STRING_MAX_SIZE
);
795 ConErrPrintf(szMsg
, err
);
800 if (!SetStdHandle (STD_ERROR_HANDLE
, hFile
))
802 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR3
, szMsg
, RC_STRING_MAX_SIZE
);
803 ConErrPrintf(szMsg
, err
);
807 if (nRedirFlags
& ERROR_APPEND
)
811 if (GetFileType (hFile
) == FILE_TYPE_DISK
)
812 SetFilePointer (hFile
, 0, &lHighPos
, FILE_END
);
815 DebugPrintf (_T("Error redirected to: %s\n"), err
);
818 else if (hOldConErr
!= INVALID_HANDLE_VALUE
)
820 /* Restore original stderr */
821 HANDLE hErr
= GetStdHandle (STD_ERROR_HANDLE
);
822 SetStdHandle (STD_ERROR_HANDLE
, hOldConErr
);
823 if (hOldConErr
!= hErr
)
825 hOldConErr
= INVALID_HANDLE_VALUE
;
829 /* process final command */
832 #ifdef FEATURE_REDIRECTION
833 /* close old stdin file */
834 #if 0 /* buggy implementation */
835 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
836 if ((hFile
[0] != INVALID_HANDLE_VALUE
) &&
837 (hFile
[0] != hOldConIn
))
839 /* delete old stdin file, if it is a real file */
840 CloseHandle (hFile
[0]);
841 hFile
[0] = INVALID_HANDLE_VALUE
;
842 DeleteFile (szFileName
[0]);
843 *szFileName
[0] = _T('\0');
846 /* Restore original STDIN */
847 if (hOldConIn
!= INVALID_HANDLE_VALUE
)
849 HANDLE hIn
= GetStdHandle (STD_INPUT_HANDLE
);
850 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
851 if (hOldConIn
!= hIn
)
853 hOldConIn
= INVALID_HANDLE_VALUE
;
858 DebugPrintf (_T("Can't restore STDIN! Is invalid!!\n"), out
);
861 #endif /* buggy implementation */
864 if (hOldConIn
!= INVALID_HANDLE_VALUE
)
866 HANDLE hIn
= GetStdHandle (STD_INPUT_HANDLE
);
867 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
868 if (hIn
== INVALID_HANDLE_VALUE
)
871 DebugPrintf (_T("Previous STDIN is invalid!!\n"));
876 if (GetFileType (hIn
) == FILE_TYPE_DISK
)
880 CloseHandle (hFile
[0]);
881 hFile
[0] = INVALID_HANDLE_VALUE
;
882 DeleteFile (szFileName
[0]);
883 *szFileName
[0] = _T('\0');
888 DebugPrintf (_T("hFile[0] and hIn dont match!!!\n"));
896 /* Restore original STDOUT */
897 if (hOldConOut
!= INVALID_HANDLE_VALUE
)
899 HANDLE hOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
900 SetStdHandle (STD_OUTPUT_HANDLE
, hOldConOut
);
901 if (hOldConOut
!= hOut
)
903 hOldConOut
= INVALID_HANDLE_VALUE
;
906 /* Restore original STDERR */
907 if (hOldConErr
!= INVALID_HANDLE_VALUE
)
909 HANDLE hErr
= GetStdHandle (STD_ERROR_HANDLE
);
910 SetStdHandle (STD_ERROR_HANDLE
, hOldConErr
);
911 if (hOldConErr
!= hErr
)
913 hOldConErr
= INVALID_HANDLE_VALUE
;
915 #endif /* FEATURE_REDIRECTION */
920 * do the prompt/input/process loop
925 ProcessInput (BOOL bFlag
)
927 TCHAR commandline
[CMDLINE_LENGTH
];
928 TCHAR readline
[CMDLINE_LENGTH
];
937 /* if no batch input then... */
938 if (!(ip
= ReadBatchLine (&bEchoThisLine
)))
943 ReadCommand (readline
, CMDLINE_LENGTH
);
945 bEchoThisLine
= FALSE
;
969 if ((tp
= FindArg (*ip
- _T('0'))))
971 cp
= _stpcpy (cp
, tp
);
979 cp
+= _stprintf (cp
, _T("%u"), nErrorLevel
);
984 tp
= _tcschr(ip
, _T('%'));
986 (tp
<= _tcschr(ip
, _T(' ')) - 1))
992 /* FIXME: Correct error handling when it can not alloc memmory */
995 if (_tcsicmp(ip
,_T("cd")) ==0)
997 TCHAR szPath
[MAX_PATH
];
998 GetCurrentDirectory (MAX_PATH
, szPath
);
999 cp
= _stpcpy (cp
, szPath
);
1003 else if (_tcsicmp(ip
,_T("time")) ==0)
1006 GetTimeFormat(LOCALE_USER_DEFAULT
, 0, NULL
, NULL
, szTime
, sizeof(szTime
));
1007 cp
= _stpcpy (cp
, szTime
);
1011 else if (_tcsicmp(ip
,_T("date")) ==0)
1015 GetDateFormat(LOCALE_USER_DEFAULT
, 0, NULL
, _T("ddd"), szDate
, sizeof (szDate
));
1016 cp
= _stpcpy (cp
, szDate
);
1017 cp
= _stpcpy (cp
, _T(" "));
1018 GetDateFormat(LOCALE_USER_DEFAULT
, DATE_SHORTDATE
, NULL
, NULL
, szDate
, sizeof (szDate
));
1019 cp
= _stpcpy (cp
, szDate
);
1023 else if (_tcsicmp(ip
,_T("random")) ==0)
1026 /* Get random number */
1027 _itot(rand(),szRand
,10);
1028 cp
= _stpcpy (cp
, szRand
);
1032 else if (_tcsicmp(ip
,_T("cmdcmdline")) ==0)
1035 /* Get random number */
1036 pargv
= GetCommandLine();
1037 cp
= _stpcpy (cp
, pargv
);
1040 /* %CMDEXTVERSION% */
1041 else if (_tcsicmp(ip
,_T("cmdextversion")) ==0)
1044 /* Set version number to 2 */
1046 cp
= _stpcpy (cp
, szVER
);
1050 else if (_tcsicmp(ip
,_T("errorlevel")) ==0)
1052 evar
= malloc ( size
* sizeof(TCHAR
));
1056 memset(evar
,0,512 * sizeof(TCHAR
));
1057 _itot(nErrorLevel
,evar
,10);
1058 cp
= _stpcpy (cp
, evar
);
1064 evar
= malloc ( size
* sizeof(TCHAR
));
1068 size
= GetEnvironmentVariable (ip
, evar
, size
);
1071 evar
= realloc(evar
,size
* sizeof(TCHAR
) );
1074 size
= GetEnvironmentVariable (ip
, evar
, size
);
1080 cp
= _stpcpy (cp
, evar
);
1102 if (_istcntrl (*ip
))
1109 /* strip trailing spaces */
1110 while ((--cp
>= commandline
) && _istspace (*cp
));
1112 *(cp
+ 1) = _T('\0');
1115 /* Echo batch file line */
1119 ConOutPuts (commandline
);
1124 ParseCommandLine (commandline
);
1125 if (bEcho
&& !bIgnoreEcho
)
1127 bIgnoreEcho
= FALSE
;
1130 while (!bCanExit
|| !bExit
);
1137 * control-break handler.
1139 BOOL WINAPI
BreakHandler (DWORD dwCtrlType
)
1142 if ((dwCtrlType
!= CTRL_C_EVENT
) &&
1143 (dwCtrlType
!= CTRL_BREAK_EVENT
))
1146 if (bChildProcessRunning
== TRUE
)
1148 GenerateConsoleCtrlEvent (CTRL_C_EVENT
,
1153 /* FIXME: Handle batch files */
1155 /* FIXME: Print "^C" */
1162 VOID
AddBreakHandler (VOID
)
1164 SetConsoleCtrlHandler ((PHANDLER_ROUTINE
)BreakHandler
, TRUE
);
1168 VOID
RemoveBreakHandler (VOID
)
1170 SetConsoleCtrlHandler ((PHANDLER_ROUTINE
)BreakHandler
, FALSE
);
1175 * show commands and options that are available.
1182 /* print command list */
1183 ConOutResPuts(STRING_CMD_HELP1
);
1186 /* print feature list */
1187 ConOutResPuts(STRING_CMD_HELP2
);
1189 #ifdef FEATURE_ALIASES
1190 ConOutResPuts(STRING_CMD_HELP3
);
1192 #ifdef FEATURE_HISTORY
1193 ConOutResPuts(STRING_CMD_HELP4
);
1195 #ifdef FEATURE_UNIX_FILENAME_COMPLETION
1196 ConOutResPuts(STRING_CMD_HELP5
);
1198 #ifdef FEATURE_DIRECTORY_STACK
1199 ConOutResPuts(STRING_CMD_HELP6
);
1201 #ifdef FEATURE_REDIRECTION
1202 ConOutResPuts(STRING_CMD_HELP7
);
1204 ConOutChar(_T('\n'));
1209 * set up global initializations and process parameters
1211 * argc - number of parameters to command.com
1212 * argv - command-line parameters
1216 Initialize (int argc
, TCHAR
* argv
[])
1218 TCHAR commandline
[CMDLINE_LENGTH
];
1219 TCHAR ModuleName
[_MAX_PATH
+ 1];
1223 //TCHAR *ptr, *cmdLine;
1229 DebugPrintf (_T("[command args:\n"));
1230 for (x
= 0; x
< argc
; x
++)
1232 DebugPrintf (_T("%d. %s\n"), x
, argv
[x
]);
1234 DebugPrintf (_T("]\n"));
1237 /* get version information */
1238 osvi
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
1239 GetVersionEx (&osvi
);
1243 /* get default input and output console handles */
1244 hOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
1245 hIn
= GetStdHandle (STD_INPUT_HANDLE
);
1248 if (argc
>= 2 && !_tcsncmp (argv
[1], _T("/?"), 2))
1250 ConOutResPaging(TRUE
,STRING_CMD_HELP8
);
1253 SetConsoleMode (hIn
, ENABLE_PROCESSED_INPUT
);
1255 #ifdef INCLUDE_CMD_CHDIR
1259 #ifdef FATURE_ALIASES
1265 for (i
= 1; i
< argc
; i
++)
1267 if (!_tcsicmp (argv
[i
], _T("/p")))
1269 if (!IsExistingFile (_T("\\autoexec.bat")))
1271 #ifdef INCLUDE_CMD_DATE
1272 cmd_date (_T(""), _T(""));
1274 #ifdef INCLUDE_CMD_TIME
1275 cmd_time (_T(""), _T(""));
1280 ParseCommandLine (_T("\\autoexec.bat"));
1284 else if (!_tcsicmp (argv
[i
], _T("/c")))
1286 /* This just runs a program and exits */
1290 _tcscpy (commandline
, argv
[i
]);
1293 _tcscat (commandline
, _T(" "));
1294 _tcscat (commandline
, argv
[i
]);
1297 ParseCommandLine(commandline
);
1298 ExitProcess (ProcessInput (TRUE
));
1305 else if (!_tcsicmp (argv
[i
], _T("/k")))
1307 /* This just runs a program and remains */
1311 _tcscpy (commandline
, argv
[i
]);
1314 _tcscat (commandline
, _T(" "));
1315 _tcscat (commandline
, argv
[i
]);
1318 ParseCommandLine(commandline
);
1321 #ifdef INCLUDE_CMD_COLOR
1322 else if (!_tcsnicmp (argv
[i
], _T("/t:"), 3))
1324 /* process /t (color) argument */
1325 wDefColor
= (WORD
)_tcstoul (&argv
[i
][3], NULL
, 16);
1327 SetScreenColor (wColor
, TRUE
);
1333 /* run cmdstart.bat */
1334 if (IsExistingFile (_T("cmdstart.bat")))
1336 ParseCommandLine (_T("cmdstart.bat"));
1338 else if (IsExistingFile (_T("\\cmdstart.bat")))
1340 ParseCommandLine (_T("\\cmdstart.bat"));
1345 /* try to run cmdstart.bat from install dir */
1348 _tcscpy (commandline
, argv
[0]);
1349 p
= _tcsrchr (commandline
, _T('\\')) + 1;
1350 _tcscpy (p
, _T("cmdstart.bat"));
1352 if (IsExistingFile (_T("commandline")))
1354 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR4
, szMsg
, RC_STRING_MAX_SIZE
);
1355 ConErrPrintf(szMsg
, commandline
);
1356 ParseCommandLine (commandline
);
1361 #ifdef FEATURE_DIR_STACK
1362 /* initialize directory stack */
1363 InitDirectoryStack ();
1367 #ifdef FEATURE_HISTORY
1368 /*initialize history*/
1372 /* Set COMSPEC environment variable */
1373 if (0 != GetModuleFileName (NULL
, ModuleName
, _MAX_PATH
+ 1))
1375 ModuleName
[_MAX_PATH
] = _T('\0');
1376 SetEnvironmentVariable (_T("COMSPEC"), ModuleName
);
1379 /* add ctrl break handler */
1384 static VOID
Cleanup (int argc
, TCHAR
*argv
[])
1387 TCHAR szMsg
[RC_STRING_MAX_SIZE
];
1390 /* run cmdexit.bat */
1391 if (IsExistingFile (_T("cmdexit.bat")))
1393 ConErrResPuts(STRING_CMD_ERROR5
);
1395 ParseCommandLine (_T("cmdexit.bat"));
1397 else if (IsExistingFile (_T("\\cmdexit.bat")))
1399 ConErrResPuts (STRING_CMD_ERROR5
);
1400 ParseCommandLine (_T("\\cmdexit.bat"));
1405 /* try to run cmdexit.bat from install dir */
1406 TCHAR commandline
[CMDLINE_LENGTH
];
1409 _tcscpy (commandline
, argv
[0]);
1410 p
= _tcsrchr (commandline
, _T('\\')) + 1;
1411 _tcscpy (p
, _T("cmdexit.bat"));
1413 if (IsExistingFile (_T("commandline")))
1415 LoadString(CMD_ModuleHandle
, STRING_CMD_ERROR4
, szMsg
, RC_STRING_MAX_SIZE
);
1416 ConErrPrintf(szMsg
, commandline
);
1417 ParseCommandLine (commandline
);
1422 #ifdef FEATURE_ALIASES
1426 #ifdef FEATURE_DIECTORY_STACK
1427 /* destroy directory stack */
1428 DestroyDirectoryStack ();
1431 #ifdef INCLUDE_CMD_CHDIR
1435 #ifdef FEATURE_HISTORY
1440 /* remove ctrl break handler */
1441 RemoveBreakHandler ();
1442 SetConsoleMode( GetStdHandle( STD_INPUT_HANDLE
),
1443 ENABLE_LINE_INPUT
| ENABLE_PROCESSED_INPUT
| ENABLE_ECHO_INPUT
);
1448 PWCHAR
* _CommandLineToArgvW(PWCHAR lpCmdLine
, int *pNumArgs
)
1450 PWCHAR
* argvw
= NULL
;
1451 PWCHAR ptr
= lpCmdLine
;
1458 while(lpCmdLine
&& *lpCmdLine
)
1460 while (iswspace(*lpCmdLine
)) lpCmdLine
++;
1463 if ((NumArgs
% 10)==0)
1465 PWCHAR
* old_argvw
= argvw
;
1466 argvw
= malloc((NumArgs
+ 10) * sizeof(PWCHAR
));
1467 memcpy(argvw
, old_argvw
, NumArgs
* sizeof(PWCHAR
));
1470 ptr
= wcschr(lpCmdLine
, L
' ');
1473 len
= ptr
- lpCmdLine
;
1477 len
= wcslen(lpCmdLine
);
1479 str
= malloc((len
+ 1) * sizeof(WCHAR
));
1480 memcpy(str
, lpCmdLine
, len
* sizeof(WCHAR
));
1487 *pNumArgs
= NumArgs
;
1499 int main (int argc
, char *argv
[])
1502 CONSOLE_SCREEN_BUFFER_INFO Info
;
1508 argv
= _CommandLineToArgvW(GetCommandLineW(), &argc
);
1510 argv
= CommandLineToArgvW(GetCommandLineW(), &argc
);
1519 hConsole
= CreateFile(_T("CONOUT$"), GENERIC_READ
|GENERIC_WRITE
,
1520 FILE_SHARE_READ
|FILE_SHARE_WRITE
, NULL
,
1521 OPEN_EXISTING
, 0, NULL
);
1522 if (GetConsoleScreenBufferInfo(hConsole
, &Info
) == FALSE
)
1524 ConOutFormatMessage(GetLastError());
1527 wColor
= Info
.wAttributes
;
1530 InputCodePage
= GetConsoleCP();
1531 OutputCodePage
= GetConsoleOutputCP();
1532 CMD_ModuleHandle
= GetModuleHandle(NULL
);
1534 /* check switches on command-line */
1535 Initialize(argc
, argv
);
1537 /* call prompt routine */
1538 nExitCode
= ProcessInput(FALSE
);
1541 /* do the cleanup */
1542 Cleanup(argc
, argv
);