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)
88 * First ReactOS release.
89 * Extended length of commandline buffers to 512.
91 * 13-Dec-1998 (Eric Kohl)
92 * Added COMSPEC environment variable.
93 * Added "/t" support (color) on cmd command line.
95 * 07-Jan-1999 (Eric Kohl)
96 * Added help text ("cmd /?").
98 * 25-Jan-1999 (Eric Kohl)
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)
105 * Replaced spawnl() by CreateProcess().
107 * 22-Oct-1999 (Eric Kohl)
108 * Added break handler.
110 * 15-Dec-1999 (Eric Kohl)
111 * Fixed current directory
113 * 28-Dec-1999 (Eric Kohl)
114 * Restore window title after program/batch execution
116 * 03-Feb-2001 (Eric Kohl)
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.
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
147 #define NT_SUCCESS(StatCode) ((NTSTATUS)(StatCode) >= 0)
150 typedef NTSTATUS (WINAPI
*NtQueryInformationProcessProc
)(HANDLE
, PROCESSINFOCLASS
,
151 PVOID
, ULONG
, PULONG
);
152 typedef NTSTATUS (WINAPI
*NtReadVirtualMemoryProc
)(HANDLE
, PVOID
, PVOID
, ULONG
, PULONG
);
154 BOOL bExit
= FALSE
; /* indicates EXIT was typed */
155 BOOL bCanExit
= TRUE
; /* indicates if this shell is exitable */
156 BOOL bCtrlBreak
= FALSE
; /* Ctrl-Break or Ctrl-C hit */
157 BOOL bIgnoreEcho
= FALSE
; /* Set this to TRUE to prevent a newline, when executing a command */
158 INT nErrorLevel
= 0; /* Errorlevel of last launched external program */
159 BOOL bChildProcessRunning
= FALSE
;
160 DWORD dwChildProcessId
= 0;
165 HANDLE CMD_ModuleHandle
;
168 static NtQueryInformationProcessProc NtQueryInformationProcessPtr
= NULL
;
169 static NtReadVirtualMemoryProc NtReadVirtualMemoryPtr
= NULL
;
171 #ifdef INCLUDE_CMD_COLOR
172 WORD wColor
; /* current color */
173 WORD wDefColor
; /* default color */
179 * insert commas into a number
182 ConvertULargeInteger (ULARGE_INTEGER num
, LPTSTR des
, INT len
, BOOL bPutSeperator
)
190 if (num
.QuadPart
== 0)
198 iTarget
= nNumberGroups
;
200 bPutSeperator
= FALSE
;
202 while (num
.QuadPart
> 0)
204 if (iTarget
== n
&& bPutSeperator
)
206 iTarget
+= nNumberGroups
+ 1;
207 temp
[31 - n
++] = cThousandSeparator
;
209 temp
[31 - n
++] = (TCHAR
)(num
.QuadPart
% 10) + _T('0');
215 memcpy(des
, temp
+ 32 - n
, n
* sizeof(TCHAR
));
222 * is character a delimeter when used on first word?
225 static BOOL
IsDelimiter (TCHAR c
)
227 return (c
== _T('/') || c
== _T('=') || c
== _T('\0') || _istspace (c
));
231 * Is a process a console process?
233 static BOOL
IsConsoleProcess(HANDLE Process
)
236 PROCESS_BASIC_INFORMATION Info
;
240 if (NULL
== NtQueryInformationProcessPtr
|| NULL
== NtReadVirtualMemoryPtr
)
245 Status
= NtQueryInformationProcessPtr (
246 Process
, ProcessBasicInformation
,
247 &Info
, sizeof(PROCESS_BASIC_INFORMATION
), NULL
);
248 if (! NT_SUCCESS(Status
))
250 WARN ("NtQueryInformationProcess failed with status %08x\n", Status
);
253 Status
= NtReadVirtualMemoryPtr (
254 Process
, Info
.PebBaseAddress
, &ProcessPeb
,
255 sizeof(PEB
), &BytesRead
);
256 if (! NT_SUCCESS(Status
) || sizeof(PEB
) != BytesRead
)
258 WARN ("Couldn't read virt mem status %08x bytes read %lu\n", Status
, BytesRead
);
262 return IMAGE_SUBSYSTEM_WINDOWS_CUI
== ProcessPeb
.ImageSubSystem
;
268 #define SHELLEXECUTETEXT "ShellExecuteW"
270 #define SHELLEXECUTETEXT "ShellExecuteA"
273 typedef HINSTANCE (WINAPI
*MYEX
)(
277 LPCTSTR lpParameters
,
284 static BOOL
RunFile(LPTSTR filename
)
290 TRACE ("RunFile(%s)\n", debugstr_aw(filename
));
291 hShell32
= LoadLibrary(_T("SHELL32.DLL"));
294 WARN ("RunFile: couldn't load SHELL32.DLL!\n");
298 hShExt
= (MYEX
)(FARPROC
)GetProcAddress(hShell32
, SHELLEXECUTETEXT
);
301 WARN ("RunFile: couldn't find ShellExecuteA/W in SHELL32.DLL!\n");
302 FreeLibrary(hShell32
);
306 TRACE ("RunFile: ShellExecuteA/W is at %x\n", hShExt
);
308 ret
= (hShExt
)(NULL
, _T("open"), filename
, NULL
, NULL
, SW_SHOWNORMAL
);
310 TRACE ("RunFile: ShellExecuteA/W returned %d\n", (DWORD
)ret
);
312 FreeLibrary(hShell32
);
313 return (((DWORD
)ret
) > 32);
319 * This command (in first) was not found in the command table
321 * Full - whole command line
322 * First - first word on command line
323 * Rest - rest of command line
327 Execute (LPTSTR Full
, LPTSTR First
, LPTSTR Rest
)
329 TCHAR
*szFullName
=NULL
;
334 TCHAR szWindowTitle
[MAX_PATH
];
335 DWORD dwExitCode
= 0;
337 TRACE ("Execute: \'%s\' \'%s\'\n", debugstr_aw(first
), debugstr_aw(rest
));
339 /* we need biger buffer that First, Rest, Full are already
340 need rewrite some code to use cmd_realloc when it need instead
341 of add 512bytes extra */
343 first
= cmd_alloc ( (_tcslen(First
) + 512) * sizeof(TCHAR
));
346 error_out_of_memory();
351 rest
= cmd_alloc ( (_tcslen(Rest
) + 512) * sizeof(TCHAR
));
355 error_out_of_memory();
360 full
= cmd_alloc ( (_tcslen(Full
) + 512) * sizeof(TCHAR
));
365 error_out_of_memory();
370 szFullName
= cmd_alloc ( (_tcslen(Full
) + 512) * sizeof(TCHAR
));
376 error_out_of_memory();
382 /* Though it was already parsed once, we have a different set of rules
383 for parsing before we pass to CreateProccess */
384 if(!_tcschr(Full
,_T('\"')))
386 _tcscpy(first
,First
);
393 BOOL bInside
= FALSE
;
398 /* find the end of the command and start of the args */
399 for(i
= 0; i
< _tcslen(first
); i
++)
401 if(!_tcsncmp(&first
[i
], _T("\""), 1))
403 if(!_tcsncmp(&first
[i
], _T(" "), 1) && !bInside
)
405 _tcscpy(rest
,&first
[i
]);
412 /* remove any slashes */
413 while(i
< _tcslen(first
))
415 if(first
[i
] == _T('\"'))
416 memmove(&first
[i
],&first
[i
+ 1], _tcslen(&first
[i
]) * sizeof(TCHAR
));
420 /* Drop quotes around it just in case there is a space */
421 _tcscpy(full
,_T("\""));
423 _tcscat(full
,_T("\" "));
427 /* check for a drive change */
428 if ((_istalpha (first
[0])) && (!_tcscmp (first
+ 1, _T(":"))))
431 if (!SetCurrentDirectory(first
))
432 /* Guess they changed disc or something, handle that gracefully and get to root */
439 working
= SetCurrentDirectory(str
);
442 if (!working
) ConErrResPuts (STRING_FREE_ERROR1
);
447 cmd_free (szFullName
);
452 /* get the PATH environment variable and parse it */
453 /* search the PATH environment variable for the binary */
454 if (!SearchForExecutable (first
, szFullName
))
456 error_bad_command ();
460 cmd_free (szFullName
);
466 GetConsoleTitle (szWindowTitle
, MAX_PATH
);
468 /* check if this is a .BAT or .CMD file */
469 dot
= _tcsrchr (szFullName
, _T('.'));
470 if (dot
&& (!_tcsicmp (dot
, _T(".bat")) || !_tcsicmp (dot
, _T(".cmd"))))
472 TRACE ("[BATCH: %s %s]\n", debugstr_aw(szFullName
), debugstr_aw(rest
));
473 Batch (szFullName
, first
, rest
);
477 /* exec the program */
478 PROCESS_INFORMATION prci
;
481 TRACE ("[EXEC: %s %s]\n", debugstr_aw(full
), debugstr_aw(rest
));
482 /* build command line for CreateProcess() */
484 /* fill startup info */
485 memset (&stui
, 0, sizeof (STARTUPINFO
));
486 stui
.cb
= sizeof (STARTUPINFO
);
487 stui
.dwFlags
= STARTF_USESHOWWINDOW
;
488 stui
.wShowWindow
= SW_SHOWDEFAULT
;
490 // return console to standard mode
491 SetConsoleMode (GetStdHandle(STD_INPUT_HANDLE
),
492 ENABLE_LINE_INPUT
| ENABLE_PROCESSED_INPUT
| ENABLE_ECHO_INPUT
);
494 if (CreateProcess (szFullName
,
499 0, /* CREATE_NEW_PROCESS_GROUP */
506 if (IsConsoleProcess(prci
.hProcess
))
508 /* FIXME: Protect this with critical section */
509 bChildProcessRunning
= TRUE
;
510 dwChildProcessId
= prci
.dwProcessId
;
512 WaitForSingleObject (prci
.hProcess
, INFINITE
);
514 /* FIXME: Protect this with critical section */
515 bChildProcessRunning
= FALSE
;
517 GetExitCodeProcess (prci
.hProcess
, &dwExitCode
);
518 nErrorLevel
= (INT
)dwExitCode
;
524 CloseHandle (prci
.hThread
);
525 CloseHandle (prci
.hProcess
);
529 TRACE ("[ShellExecute: %s]\n", debugstr_aw(full
));
530 // See if we can run this with ShellExecute() ie myfile.xls
533 TRACE ("[ShellExecute failed!: %s]\n", debugstr_aw(full
));
534 error_bad_command ();
542 // restore console mode
544 GetStdHandle( STD_INPUT_HANDLE
),
545 ENABLE_PROCESSED_INPUT
);
548 /* Get code page if it has been change */
549 InputCodePage
= GetConsoleCP();
550 OutputCodePage
= GetConsoleOutputCP();
551 SetConsoleTitle (szWindowTitle
);
556 cmd_free (szFullName
);
561 * look through the internal commands and determine whether or not this
562 * command is one of them. If it is, call the command. If not, call
563 * execute to run it as an external program.
565 * line - the command line of the program to run
570 DoCommand (LPTSTR line
)
572 TCHAR
*com
= NULL
; /* the first word in the command */
575 LPTSTR rest
; /* pointer to the rest of the command line */
579 TRACE ("DoCommand: (\'%s\')\n", debugstr_aw(line
));
581 com
= cmd_alloc( (_tcslen(line
) +512)*sizeof(TCHAR
) );
584 error_out_of_memory();
589 /* Skip over initial white space */
590 while (_istspace (*line
))
596 /* Anything to do ? */
599 if (*rest
== _T('"'))
601 /* treat quoted words specially */
605 while(*rest
!= _T('\0') && *rest
!= _T('"'))
606 *cp
++ = _totlower (*rest
++);
607 if (*rest
== _T('"'))
612 while (!IsDelimiter (*rest
))
613 *cp
++ = _totlower (*rest
++);
617 /* Terminate first word */
620 /* Do not limit commands to MAX_PATH */
622 if(_tcslen(com) > MAX_PATH)
630 /* Skip over whitespace to rest of line, exclude 'echo' command */
631 if (_tcsicmp (com
, _T("echo")))
633 while (_istspace (*rest
))
637 /* Scan internal command table */
638 for (cmdptr
= cmds
;; cmdptr
++)
640 /* If end of table execute ext cmd */
641 if (cmdptr
->name
== NULL
)
643 Execute (line
, com
, rest
);
647 if (!_tcscmp (com
, cmdptr
->name
))
649 cmdptr
->func (com
, rest
);
653 /* The following code handles the case of commands like CD which
654 * are recognised even when the command name and parameter are
655 * not space separated.
661 /* Get length of command name */
662 cl
= _tcslen (cmdptr
->name
);
664 if ((cmdptr
->flags
& CMD_SPECIAL
) &&
665 (!_tcsncmp (cmdptr
->name
, com
, cl
)) &&
666 (_tcschr (_T("\\.-"), *(com
+ cl
))))
668 /* OK its one of the specials...*/
670 /* Terminate first word properly */
673 /* Call with new rest */
674 cmdptr
->func (com
, cstart
+ cl
);
684 * process the command line and execute the appropriate functions
685 * full input/output redirection and piping are supported
688 VOID
ParseCommandLine (LPTSTR cmd
)
690 TCHAR cmdline
[CMDLINE_LENGTH
];
692 #ifdef FEATURE_REDIRECTION
693 TCHAR in
[CMDLINE_LENGTH
] = _T("");
694 TCHAR out
[CMDLINE_LENGTH
] = _T("");
695 TCHAR err
[CMDLINE_LENGTH
] = _T("");
696 TCHAR szTempPath
[MAX_PATH
] = _T(".\\");
697 TCHAR szFileName
[2][MAX_PATH
] = {_T(""), _T("")};
698 HANDLE hFile
[2] = {INVALID_HANDLE_VALUE
, INVALID_HANDLE_VALUE
};
704 BOOL bNewBatch
= TRUE
;
708 #endif /* FEATURE_REDIRECTION */
710 _tcscpy (cmdline
, cmd
);
713 TRACE ("ParseCommandLine: (\'%s\')\n", debugstr_aw(s
));
715 #ifdef FEATURE_ALIASES
716 /* expand all aliases */
717 ExpandAlias (s
, CMDLINE_LENGTH
);
718 #endif /* FEATURE_ALIAS */
720 #ifdef FEATURE_REDIRECTION
721 /* find the temp path to store temporary files */
722 Length
= GetTempPath (MAX_PATH
, szTempPath
);
723 if (Length
> 0 && Length
< MAX_PATH
)
725 Attributes
= GetFileAttributes(szTempPath
);
726 if (Attributes
== 0xffffffff ||
727 !(Attributes
& FILE_ATTRIBUTE_DIRECTORY
))
732 if (Length
== 0 || Length
>= MAX_PATH
)
734 _tcscpy(szTempPath
, _T(".\\"));
736 if (szTempPath
[_tcslen (szTempPath
) - 1] != _T('\\'))
737 _tcscat (szTempPath
, _T("\\"));
739 /* get the redirections from the command line */
740 num
= GetRedirection (s
, in
, out
, err
, &nRedirFlags
);
742 /* more efficient, but do we really need to do this? */
743 for (t
= in
; _istspace (*t
); t
++)
747 for (t
= out
; _istspace (*t
); t
++)
751 for (t
= err
; _istspace (*t
); t
++)
755 if(bc
&& !_tcslen (in
) && _tcslen (bc
->In
))
757 if(bc
&& !out
[0] && _tcslen(bc
->Out
))
759 nRedirFlags
|= OUTPUT_APPEND
;
760 _tcscpy(out
, bc
->Out
);
762 if(bc
&& !_tcslen (err
) && _tcslen (bc
->Err
))
764 nRedirFlags
|= ERROR_APPEND
;
765 _tcscpy(err
, bc
->Err
);
768 /* Set up the initial conditions ... */
769 /* preserve STDIN, STDOUT and STDERR handles */
770 hOldConIn
= GetStdHandle (STD_INPUT_HANDLE
);
771 hOldConOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
772 hOldConErr
= GetStdHandle (STD_ERROR_HANDLE
);
778 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
780 /* we need make sure the LastError msg is zero before calling CreateFile */
783 /* Set up pipe for the standard input handler */
784 hFile
= CreateFile (in
, GENERIC_READ
, FILE_SHARE_READ
, &sa
, OPEN_EXISTING
,
785 FILE_ATTRIBUTE_NORMAL
, NULL
);
786 if (hFile
== INVALID_HANDLE_VALUE
)
788 ConErrResPrintf(STRING_CMD_ERROR1
, in
);
792 if (!SetStdHandle (STD_INPUT_HANDLE
, hFile
))
794 ConErrResPrintf(STRING_CMD_ERROR1
, in
);
797 TRACE ("Input redirected from: %s\n", debugstr_aw(in
));
800 /* Now do all but the last pipe command */
801 *szFileName
[0] = _T('\0');
802 hFile
[0] = INVALID_HANDLE_VALUE
;
806 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
808 /* Create unique temporary file name */
809 GetTempFileName (szTempPath
, _T("CMD"), 0, szFileName
[1]);
811 /* we need make sure the LastError msg is zero before calling CreateFile */
814 /* Set current stdout to temporary file */
815 hFile
[1] = CreateFile (szFileName
[1], GENERIC_WRITE
, 0, &sa
,
816 TRUNCATE_EXISTING
, FILE_ATTRIBUTE_TEMPORARY
, NULL
);
818 if (hFile
[1] == INVALID_HANDLE_VALUE
)
820 ConErrResPrintf(STRING_CMD_ERROR2
);
824 SetStdHandle (STD_OUTPUT_HANDLE
, hFile
[1]);
828 /* close stdout file */
829 SetStdHandle (STD_OUTPUT_HANDLE
, hOldConOut
);
830 if ((hFile
[1] != INVALID_HANDLE_VALUE
) && (hFile
[1] != hOldConOut
))
832 CloseHandle (hFile
[1]);
833 hFile
[1] = INVALID_HANDLE_VALUE
;
836 /* close old stdin file */
837 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
838 if ((hFile
[0] != INVALID_HANDLE_VALUE
) && (hFile
[0] != hOldConIn
))
840 /* delete old stdin file, if it is a real file */
841 CloseHandle (hFile
[0]);
842 hFile
[0] = INVALID_HANDLE_VALUE
;
843 DeleteFile (szFileName
[0]);
844 *szFileName
[0] = _T('\0');
847 /* copy stdout file name to stdin file name */
848 _tcscpy (szFileName
[0], szFileName
[1]);
849 *szFileName
[1] = _T('\0');
851 /* we need make sure the LastError msg is zero before calling CreateFile */
854 /* open new stdin file */
855 hFile
[0] = CreateFile (szFileName
[0], GENERIC_READ
, 0, &sa
,
856 OPEN_EXISTING
, FILE_ATTRIBUTE_TEMPORARY
, NULL
);
857 SetStdHandle (STD_INPUT_HANDLE
, hFile
[0]);
859 s
= s
+ _tcslen (s
) + 1;
862 /* Now set up the end conditions... */
863 /* redirect STDOUT */
866 /* Final output to here */
868 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
870 /* we need make sure the LastError msg is zero before calling CreateFile */
873 hFile
= CreateFile (out
, GENERIC_WRITE
, FILE_SHARE_WRITE
| FILE_SHARE_READ
| FILE_SHARE_DELETE
, &sa
,
874 (nRedirFlags
& OUTPUT_APPEND
) ? OPEN_ALWAYS
: CREATE_ALWAYS
,
875 FILE_ATTRIBUTE_NORMAL
| FILE_FLAG_WRITE_THROUGH
, NULL
);
877 if (hFile
== INVALID_HANDLE_VALUE
)
879 INT size
= _tcslen(out
)-1;
881 if (out
[size
] != _T(':'))
883 ConErrResPrintf(STRING_CMD_ERROR3
, out
);
888 hFile
= CreateFile (out
, GENERIC_WRITE
, FILE_SHARE_WRITE
| FILE_SHARE_READ
| FILE_SHARE_DELETE
, &sa
,
889 (nRedirFlags
& OUTPUT_APPEND
) ? OPEN_ALWAYS
: CREATE_ALWAYS
,
890 FILE_ATTRIBUTE_NORMAL
| FILE_FLAG_WRITE_THROUGH
, NULL
);
892 if (hFile
== INVALID_HANDLE_VALUE
)
894 ConErrResPrintf(STRING_CMD_ERROR3
, out
);
900 if (!SetStdHandle (STD_OUTPUT_HANDLE
, hFile
))
902 ConErrResPrintf(STRING_CMD_ERROR3
, out
);
906 if (nRedirFlags
& OUTPUT_APPEND
)
910 if (GetFileType (hFile
) == FILE_TYPE_DISK
)
911 SetFilePointer (hFile
, 0, &lHighPos
, FILE_END
);
913 TRACE ("Output redirected to: %s\n", debugstr_aw(out
));
915 else if (hOldConOut
!= INVALID_HANDLE_VALUE
)
917 /* Restore original stdout */
918 HANDLE hOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
919 SetStdHandle (STD_OUTPUT_HANDLE
, hOldConOut
);
920 if (hOldConOut
!= hOut
)
922 hOldConOut
= INVALID_HANDLE_VALUE
;
925 /* redirect STDERR */
928 /* Final output to here */
930 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
932 if (!_tcscmp (err
, out
))
934 TRACE ("Stdout and stderr will use the same file!!\n");
935 DuplicateHandle (GetCurrentProcess (),
936 GetStdHandle (STD_OUTPUT_HANDLE
),
937 GetCurrentProcess (),
938 &hFile
, 0, TRUE
, DUPLICATE_SAME_ACCESS
);
942 hFile
= CreateFile (err
,
944 FILE_SHARE_WRITE
| FILE_SHARE_READ
| FILE_SHARE_DELETE
,
946 (nRedirFlags
& ERROR_APPEND
) ? OPEN_ALWAYS
: CREATE_ALWAYS
,
947 FILE_ATTRIBUTE_NORMAL
| FILE_FLAG_WRITE_THROUGH
,
949 if (hFile
== INVALID_HANDLE_VALUE
)
951 ConErrResPrintf(STRING_CMD_ERROR3
, err
);
956 if (!SetStdHandle (STD_ERROR_HANDLE
, hFile
))
958 ConErrResPrintf(STRING_CMD_ERROR3
, err
);
962 if (nRedirFlags
& ERROR_APPEND
)
966 if (GetFileType (hFile
) == FILE_TYPE_DISK
)
967 SetFilePointer (hFile
, 0, &lHighPos
, FILE_END
);
969 TRACE ("Error redirected to: %s\n", debugstr_aw(err
));
971 else if (hOldConErr
!= INVALID_HANDLE_VALUE
)
973 /* Restore original stderr */
974 HANDLE hErr
= GetStdHandle (STD_ERROR_HANDLE
);
975 SetStdHandle (STD_ERROR_HANDLE
, hOldConErr
);
976 if (hOldConErr
!= hErr
)
978 hOldConErr
= INVALID_HANDLE_VALUE
;
985 /* process final command */
988 #ifdef FEATURE_REDIRECTION
990 AddBatchRedirection(in
, out
, err
);
991 /* close old stdin file */
992 #if 0 /* buggy implementation */
993 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
994 if ((hFile
[0] != INVALID_HANDLE_VALUE
) &&
995 (hFile
[0] != hOldConIn
))
997 /* delete old stdin file, if it is a real file */
998 CloseHandle (hFile
[0]);
999 hFile
[0] = INVALID_HANDLE_VALUE
;
1000 DeleteFile (szFileName
[0]);
1001 *szFileName
[0] = _T('\0');
1004 /* Restore original STDIN */
1005 if (hOldConIn
!= INVALID_HANDLE_VALUE
)
1007 HANDLE hIn
= GetStdHandle (STD_INPUT_HANDLE
);
1008 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
1009 if (hOldConIn
!= hIn
)
1011 hOldConIn
= INVALID_HANDLE_VALUE
;
1015 WARN ("Can't restore STDIN! Is invalid!!\n", out
);
1017 #endif /* buggy implementation */
1020 if (hOldConIn
!= INVALID_HANDLE_VALUE
)
1022 HANDLE hIn
= GetStdHandle (STD_INPUT_HANDLE
);
1023 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
1024 if (hIn
== INVALID_HANDLE_VALUE
)
1026 WARN ("Previous STDIN is invalid!!\n");
1030 if (GetFileType (hIn
) == FILE_TYPE_DISK
)
1032 if (hFile
[0] == hIn
)
1034 CloseHandle (hFile
[0]);
1035 hFile
[0] = INVALID_HANDLE_VALUE
;
1036 DeleteFile (szFileName
[0]);
1037 *szFileName
[0] = _T('\0');
1041 WARN ("hFile[0] and hIn dont match!!!\n");
1048 /* Restore original STDOUT */
1049 if (hOldConOut
!= INVALID_HANDLE_VALUE
)
1051 HANDLE hOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
1052 SetStdHandle (STD_OUTPUT_HANDLE
, hOldConOut
);
1053 if (hOldConOut
!= hOut
)
1055 hOldConOut
= INVALID_HANDLE_VALUE
;
1058 /* Restore original STDERR */
1059 if (hOldConErr
!= INVALID_HANDLE_VALUE
)
1061 HANDLE hErr
= GetStdHandle (STD_ERROR_HANDLE
);
1062 SetStdHandle (STD_ERROR_HANDLE
, hOldConErr
);
1063 if (hOldConErr
!= hErr
)
1065 hOldConErr
= INVALID_HANDLE_VALUE
;
1067 #endif /* FEATURE_REDIRECTION */
1071 GrowIfNecessary_dbg ( UINT needed
, LPTSTR
* ret
, UINT
* retlen
, const char *file
, int line
)
1073 if ( *ret
&& needed
< *retlen
)
1079 *ret
= (LPTSTR
)cmd_alloc_dbg ( *retlen
* sizeof(TCHAR
), file
, line
);
1081 *ret
= (LPTSTR
)cmd_alloc ( *retlen
* sizeof(TCHAR
) );
1084 SetLastError ( ERROR_OUTOFMEMORY
);
1085 return *ret
!= NULL
;
1087 #define GrowIfNecessary(x, y, z) GrowIfNecessary_dbg(x, y, z, __FILE__, __LINE__)
1090 GetEnvVarOrSpecial ( LPCTSTR varName
)
1092 static LPTSTR ret
= NULL
;
1093 static UINT retlen
= 0;
1095 TCHAR varNameFixed
[MAX_PATH
];
1096 TCHAR ReturnValue
[MAX_PATH
];
1100 INT StringPart
[1] = {0};
1102 position
= _tcsstr(varName
, _T(":~"));
1104 _tcsncpy(varNameFixed
, varName
, (int) (position
- varName
));
1106 _tcscpy(varNameFixed
, varName
);
1108 size
= GetEnvironmentVariable ( varNameFixed
, ret
, retlen
);
1109 if ( size
> retlen
)
1111 if ( !GrowIfNecessary ( size
, &ret
, &retlen
) )
1113 size
= GetEnvironmentVariable ( varNameFixed
, ret
, retlen
);
1120 if (_tcschr(position
, _T(',')) != NULL
)
1122 Token
= _tcstok(position
, _T(","));
1123 while ((Token
!= NULL
) && (i
< 2))
1125 StringPart
[i
] = _ttoi(Token
);
1127 Token
= _tcstok (NULL
, _T(","));
1131 if (StringPart
[1] < 0)
1132 StringPart
[1] = _tcslen(ret
+ StringPart
[0]) + StringPart
[1];
1133 _tcsncpy(ReturnValue
, ret
+ StringPart
[0], StringPart
[1]);
1134 _tcscpy(ret
, ReturnValue
);
1143 /* env var doesn't exist, look for a "special" one */
1145 if (_tcsicmp(varNameFixed
,_T("cd")) ==0)
1147 size
= GetCurrentDirectory ( retlen
, ret
);
1148 if ( size
> retlen
)
1150 if ( !GrowIfNecessary ( size
, &ret
, &retlen
) )
1152 size
= GetCurrentDirectory ( retlen
, ret
);
1159 else if (_tcsicmp(varNameFixed
,_T("time")) ==0)
1162 if ( !GrowIfNecessary ( MAX_PATH
, &ret
, &retlen
) )
1165 _sntprintf ( ret
, retlen
, _T("%02d%c%02d%c%02d%c%02d"),
1166 t
.wHour
, cTimeSeparator
, t
.wMinute
, cTimeSeparator
,
1167 t
.wSecond
, cDecimalSeparator
, t
.wMilliseconds
/ 10);
1171 else if (_tcsicmp(varNameFixed
,_T("date")) ==0)
1174 if ( !GrowIfNecessary ( GetDateFormat(LOCALE_USER_DEFAULT
, DATE_SHORTDATE
, NULL
, NULL
, NULL
, 0), &ret
, &retlen
) )
1177 size
= GetDateFormat(LOCALE_USER_DEFAULT
, DATE_SHORTDATE
, NULL
, NULL
, ret
, retlen
);
1185 else if (_tcsicmp(varNameFixed
,_T("random")) ==0)
1187 if ( !GrowIfNecessary ( MAX_PATH
, &ret
, &retlen
) )
1189 /* Get random number */
1190 _itot(rand(),ret
,10);
1195 else if (_tcsicmp(varNameFixed
,_T("cmdcmdline")) ==0)
1197 return GetCommandLine();
1200 /* %CMDEXTVERSION% */
1201 else if (_tcsicmp(varNameFixed
,_T("cmdextversion")) ==0)
1203 if ( !GrowIfNecessary ( MAX_PATH
, &ret
, &retlen
) )
1205 /* Set version number to 2 */
1211 else if (_tcsicmp(varNameFixed
,_T("errorlevel")) ==0)
1213 if ( !GrowIfNecessary ( MAX_PATH
, &ret
, &retlen
) )
1215 _itot(nErrorLevel
,ret
,10);
1219 GrowIfNecessary(_tcslen(varNameFixed
) + 3, &ret
, &retlen
);
1220 _stprintf(ret
,_T("%%%s%%"),varNameFixed
);
1221 return ret
; /* not found - return orginal string */
1225 GetParsedEnvVar ( LPCTSTR varName
, UINT
* varNameLen
, BOOL ModeSetA
)
1227 static LPTSTR ret
= NULL
;
1228 static UINT retlen
= 0;
1238 if ( (*varName
!= '!') && (*varName
++ != '%') )
1248 if (_tcsncicmp(varName
, _T("dp0"), 3) == 0)
1252 return bc
->BatchFilePath
;
1264 if ((tmp
= FindArg (*varName
- _T('0'))))
1270 if ( !GrowIfNecessary ( _tcslen(tmp
)+1, &ret
, &retlen
) )
1272 _tcscpy ( ret
, tmp
);
1275 if ( !GrowIfNecessary ( 3, &ret
, &retlen
) )
1288 // No batch file to see here, move along
1290 if ( !GrowIfNecessary ( 3, &ret
, &retlen
) )
1301 // Copy over the raw params(not including the batch file name
1303 if ( !GrowIfNecessary ( _tcslen(bc
->raw_params
)+1, &ret
, &retlen
) )
1307 _tcscpy ( ret
, bc
->raw_params
);
1311 if ( !GrowIfNecessary ( 2, &ret
, &retlen
) )
1320 /* TODO FIXME 10 is only max size for 32-bit */
1321 if ( !GrowIfNecessary ( 11, &ret
, &retlen
) )
1323 _sntprintf ( ret
, retlen
, _T("%u"), nErrorLevel
);
1331 /* HACK for set/a */
1332 if ( !GrowIfNecessary ( 2, &ret
, &retlen
) )
1340 p
= _tcschr ( varName
, c
);
1343 SetLastError ( ERROR_INVALID_PARAMETER
);
1348 *varNameLen
= size
+ 2;
1349 p
= alloca ( (size
+1) * sizeof(TCHAR
) );
1350 memmove ( p
, varName
, size
* sizeof(TCHAR
) );
1353 return GetEnvVarOrSpecial ( varName
);
1358 * do the prompt/input/process loop
1363 ProcessInput (BOOL bFlag
)
1365 TCHAR commandline
[CMDLINE_LENGTH
];
1366 TCHAR readline
[CMDLINE_LENGTH
];
1376 /* if no batch input then... */
1377 if (!(ip
= ReadBatchLine (&bEchoThisLine
)))
1382 ReadCommand (readline
, CMDLINE_LENGTH
);
1384 bEchoThisLine
= FALSE
;
1392 /* skip leading blanks */
1393 while ( _istspace(*ip
) )
1400 if ( (*ip
== _T('%')) || (*ip
== _T('!')) )
1403 LPCTSTR envVal
= GetParsedEnvVar ( ip
, &envNameLen
, bModeSetA
);
1407 cp
= _stpcpy ( cp
, envVal
);
1411 if (*ip
!= _T('\0') && (_istcntrl (*ip
)))
1415 /* HACK HACK HACK check whether bModeSetA needs to be toggled */
1418 tmp
+= _tcsspn(tmp
,_T(" \t"));
1419 /* first we find and skip and pre-redirections... */
1421 ( _tcschr(_T("<>"),*tmp
)
1422 || !_tcsncmp(tmp
,_T("1>"),2)
1423 || !_tcsncmp(tmp
,_T("2>"),2) ))
1425 if ( _istdigit(*tmp
) )
1429 tmp
+= _tcsspn(tmp
,_T(" \t"));
1430 if ( *tmp
== _T('\"') )
1432 tmp
= _tcschr(tmp
+1,_T('\"'));
1437 tmp
= _tcspbrk(tmp
,_T(" \t"));
1439 tmp
+= _tcsspn(tmp
,_T(" \t"));
1441 /* we should now be pointing to the actual command
1442 * (if there is one yet)*/
1445 /* if we're currently substituting ( which is default )
1446 * check to see if we've parsed out a set/a. if so, we
1447 * need to disable substitution until we come across a
1451 /* look for set /a */
1452 if ( !_tcsnicmp(tmp
,_T("set"),3) )
1455 tmp
+= _tcsspn(tmp
,_T(" \t"));
1456 if ( !_tcsnicmp(tmp
,_T("/a"),2) )
1460 /* if we're not currently substituting, it means we're
1461 * already inside a set /a. now we need to look for
1462 * a redirection in order to turn redirection back on */
1465 /* look for redirector of some kind after the command */
1466 while ( (tmp
= _tcspbrk ( tmp
, _T("^<>|") )) )
1468 if ( *tmp
== _T('^') )
1470 if ( _tcschr(_T("<>|&"), *++tmp
) && *tmp
)
1486 /* Echo batch file line */
1490 ConOutPuts (commandline
);
1493 if (!CheckCtrlBreak(BREAK_INPUT
) && *commandline
)
1495 ParseCommandLine (commandline
);
1496 if (bEcho
&& !bIgnoreEcho
&& (!bIsBatch
|| bEchoThisLine
))
1498 bIgnoreEcho
= FALSE
;
1501 while (!bCanExit
|| !bExit
);
1508 * control-break handler.
1510 BOOL WINAPI
BreakHandler (DWORD dwCtrlType
)
1515 static BOOL SelfGenerated
= FALSE
;
1517 if ((dwCtrlType
!= CTRL_C_EVENT
) &&
1518 (dwCtrlType
!= CTRL_BREAK_EVENT
))
1526 SelfGenerated
= FALSE
;
1531 if (bChildProcessRunning
== TRUE
)
1533 SelfGenerated
= TRUE
;
1534 GenerateConsoleCtrlEvent (dwCtrlType
, 0);
1539 rec
.EventType
= KEY_EVENT
;
1540 rec
.Event
.KeyEvent
.bKeyDown
= TRUE
;
1541 rec
.Event
.KeyEvent
.wRepeatCount
= 1;
1542 rec
.Event
.KeyEvent
.wVirtualKeyCode
= _T('C');
1543 rec
.Event
.KeyEvent
.wVirtualScanCode
= _T('C') - 35;
1544 rec
.Event
.KeyEvent
.uChar
.AsciiChar
= _T('C');
1545 rec
.Event
.KeyEvent
.uChar
.UnicodeChar
= _T('C');
1546 rec
.Event
.KeyEvent
.dwControlKeyState
= RIGHT_CTRL_PRESSED
;
1555 /* FIXME: Handle batch files */
1557 //ConOutPrintf(_T("^C"));
1564 VOID
AddBreakHandler (VOID
)
1566 SetConsoleCtrlHandler ((PHANDLER_ROUTINE
)BreakHandler
, TRUE
);
1570 VOID
RemoveBreakHandler (VOID
)
1572 SetConsoleCtrlHandler ((PHANDLER_ROUTINE
)BreakHandler
, FALSE
);
1577 * show commands and options that are available.
1584 /* print command list */
1585 ConOutResPuts(STRING_CMD_HELP1
);
1588 /* print feature list */
1589 ConOutResPuts(STRING_CMD_HELP2
);
1591 #ifdef FEATURE_ALIASES
1592 ConOutResPuts(STRING_CMD_HELP3
);
1594 #ifdef FEATURE_HISTORY
1595 ConOutResPuts(STRING_CMD_HELP4
);
1597 #ifdef FEATURE_UNIX_FILENAME_COMPLETION
1598 ConOutResPuts(STRING_CMD_HELP5
);
1600 #ifdef FEATURE_DIRECTORY_STACK
1601 ConOutResPuts(STRING_CMD_HELP6
);
1603 #ifdef FEATURE_REDIRECTION
1604 ConOutResPuts(STRING_CMD_HELP7
);
1606 ConOutChar(_T('\n'));
1611 ExecuteAutoRunFile (VOID
)
1613 TCHAR autorun
[MAX_PATH
];
1614 DWORD len
= MAX_PATH
;
1617 if( RegOpenKeyEx(HKEY_LOCAL_MACHINE
,
1618 _T("SOFTWARE\\Microsoft\\Command Processor"),
1621 &hkey
) == ERROR_SUCCESS
)
1623 if(RegQueryValueEx(hkey
,
1628 &len
) == ERROR_SUCCESS
)
1630 ParseCommandLine (autorun
);
1638 * set up global initializations and process parameters
1640 * argc - number of parameters to command.com
1641 * argv - command-line parameters
1645 Initialize (int argc
, const TCHAR
* argv
[])
1647 TCHAR commandline
[CMDLINE_LENGTH
];
1648 TCHAR ModuleName
[_MAX_PATH
+ 1];
1653 //TCHAR *ptr, *cmdLine;
1655 /* get version information */
1656 osvi
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
1657 GetVersionEx (&osvi
);
1659 /* Some people like to run ReactOS cmd.exe on Win98, it helps in the
1660 * build process. So don't link implicitly against ntdll.dll, load it
1661 * dynamically instead */
1663 if (osvi
.dwPlatformId
== VER_PLATFORM_WIN32_NT
)
1665 /* ntdll is always present on NT */
1666 NtDllModule
= GetModuleHandle(TEXT("ntdll.dll"));
1670 /* not all 9x versions have a ntdll.dll, try to load it */
1671 NtDllModule
= LoadLibrary(TEXT("ntdll.dll"));
1674 if (NtDllModule
!= NULL
)
1676 NtQueryInformationProcessPtr
= (NtQueryInformationProcessProc
)GetProcAddress(NtDllModule
, "NtQueryInformationProcess");
1677 NtReadVirtualMemoryPtr
= (NtReadVirtualMemoryProc
)GetProcAddress(NtDllModule
, "NtReadVirtualMemory");
1681 TRACE ("[command args:\n");
1682 for (i
= 0; i
< argc
; i
++)
1684 TRACE ("%d. %s\n", i
, debugstr_aw(argv
[i
]));
1690 /* get default input and output console handles */
1691 hOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
1692 hIn
= GetStdHandle (STD_INPUT_HANDLE
);
1694 /* Set EnvironmentVariable PROMPT if it does not exists any env value.
1695 for you can change the EnvirommentVariable for prompt before cmd start
1696 this patch are not 100% right, if it does not exists a PROMPT value cmd should use
1697 $P$G as defualt not set EnvirommentVariable PROMPT to $P$G if it does not exists */
1698 if (GetEnvironmentVariable(_T("PROMPT"),lpBuffer
, sizeof(lpBuffer
) / sizeof(lpBuffer
[0])) == 0)
1699 SetEnvironmentVariable (_T("PROMPT"), _T("$P$G"));
1702 if (argc
>= 2 && !_tcsncmp (argv
[1], _T("/?"), 2))
1704 ConOutResPaging(TRUE
,STRING_CMD_HELP8
);
1707 SetConsoleMode (hIn
, ENABLE_PROCESSED_INPUT
);
1709 #ifdef INCLUDE_CMD_CHDIR
1715 for (i
= 1; i
< argc
; i
++)
1717 if (!_tcsicmp (argv
[i
], _T("/p")))
1719 if (!IsExistingFile (_T("\\autoexec.bat")))
1721 #ifdef INCLUDE_CMD_DATE
1722 cmd_date (_T(""), _T(""));
1724 #ifdef INCLUDE_CMD_TIME
1725 cmd_time (_T(""), _T(""));
1730 ParseCommandLine (_T("\\autoexec.bat"));
1734 else if (!_tcsicmp (argv
[i
], _T("/c")))
1736 /* This just runs a program and exits */
1740 _tcscpy (commandline
, argv
[i
]);
1743 _tcscat (commandline
, _T(" "));
1744 _tcscat (commandline
, argv
[i
]);
1747 ParseCommandLine(commandline
);
1748 cmd_exit (ProcessInput (TRUE
));
1755 else if (!_tcsicmp (argv
[i
], _T("/k")))
1757 /* This just runs a program and remains */
1761 _tcscpy (commandline
, _T("\""));
1762 _tcscat (commandline
, argv
[i
]);
1763 _tcscat (commandline
, _T("\""));
1766 _tcscat (commandline
, _T(" "));
1767 _tcscat (commandline
, argv
[i
]);
1769 ParseCommandLine(commandline
);
1772 #ifdef INCLUDE_CMD_COLOR
1773 else if (!_tcsnicmp (argv
[i
], _T("/t:"), 3))
1775 /* process /t (color) argument */
1776 wDefColor
= (WORD
)_tcstoul (&argv
[i
][3], NULL
, 16);
1778 SetScreenColor (wColor
, TRUE
);
1785 /* Display a simple version string */
1786 ConOutPrintf(_T("ReactOS Operating System [Version %s-%s]\n"),
1787 _T(KERNEL_RELEASE_STR
),
1788 _T(KERNEL_VERSION_BUILD_STR
));
1790 ConOutPuts (_T("(C) Copyright 1998-") _T(COPYRIGHT_YEAR
) _T(" ReactOS Team.\n"));
1793 ExecuteAutoRunFile ();
1795 #ifdef FEATURE_DIR_STACK
1796 /* initialize directory stack */
1797 InitDirectoryStack ();
1801 #ifdef FEATURE_HISTORY
1802 /*initialize history*/
1806 /* Set COMSPEC environment variable */
1807 if (0 != GetModuleFileName (NULL
, ModuleName
, _MAX_PATH
+ 1))
1809 ModuleName
[_MAX_PATH
] = _T('\0');
1810 SetEnvironmentVariable (_T("COMSPEC"), ModuleName
);
1813 /* add ctrl break handler */
1818 static VOID
Cleanup (int argc
, const TCHAR
*argv
[])
1820 /* run cmdexit.bat */
1821 if (IsExistingFile (_T("cmdexit.bat")))
1823 ConErrResPuts(STRING_CMD_ERROR5
);
1825 ParseCommandLine (_T("cmdexit.bat"));
1827 else if (IsExistingFile (_T("\\cmdexit.bat")))
1829 ConErrResPuts (STRING_CMD_ERROR5
);
1830 ParseCommandLine (_T("\\cmdexit.bat"));
1833 #ifdef FEATURE_DIECTORY_STACK
1834 /* destroy directory stack */
1835 DestroyDirectoryStack ();
1838 #ifdef INCLUDE_CMD_CHDIR
1842 #ifdef FEATURE_HISTORY
1847 /* remove ctrl break handler */
1848 RemoveBreakHandler ();
1849 SetConsoleMode( GetStdHandle( STD_INPUT_HANDLE
),
1850 ENABLE_LINE_INPUT
| ENABLE_PROCESSED_INPUT
| ENABLE_ECHO_INPUT
);
1852 if (NtDllModule
!= NULL
)
1854 FreeLibrary(NtDllModule
);
1861 int cmd_main (int argc
, const TCHAR
*argv
[])
1863 TCHAR startPath
[MAX_PATH
];
1864 CONSOLE_SCREEN_BUFFER_INFO Info
;
1867 GetCurrentDirectory(MAX_PATH
,startPath
);
1874 hConsole
= CreateFile(_T("CONOUT$"), GENERIC_READ
|GENERIC_WRITE
,
1875 FILE_SHARE_READ
|FILE_SHARE_WRITE
, NULL
,
1876 OPEN_EXISTING
, 0, NULL
);
1877 if (GetConsoleScreenBufferInfo(hConsole
, &Info
) == FALSE
)
1879 ConErrFormatMessage(GetLastError());
1882 wColor
= Info
.wAttributes
;
1885 InputCodePage
= GetConsoleCP();
1886 OutputCodePage
= GetConsoleOutputCP();
1887 CMD_ModuleHandle
= GetModuleHandle(NULL
);
1889 /* check switches on command-line */
1890 Initialize(argc
, argv
);
1892 /* call prompt routine */
1893 nExitCode
= ProcessInput(FALSE
);
1895 /* do the cleanup */
1896 Cleanup(argc
, argv
);
1898 cmd_exit(nExitCode
);