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 BOOL bUnicodeOutput
= FALSE
;
161 BOOL bDisableBatchEcho
= FALSE
;
162 BOOL bDelayedExpansion
= FALSE
;
163 DWORD dwChildProcessId
= 0;
167 LPTSTR lpOriginalEnvironment
;
168 HANDLE CMD_ModuleHandle
;
170 static NtQueryInformationProcessProc NtQueryInformationProcessPtr
= NULL
;
171 static NtReadVirtualMemoryProc NtReadVirtualMemoryPtr
= NULL
;
173 #ifdef INCLUDE_CMD_COLOR
174 WORD wDefColor
; /* default color */
180 * insert commas into a number
183 ConvertULargeInteger(ULONGLONG num
, LPTSTR des
, INT len
, BOOL bPutSeperator
)
185 TCHAR temp
[39]; /* maximum length with nNumberGroups == 1 */
192 iTarget
= nNumberGroups
;
194 bPutSeperator
= FALSE
;
198 if (iTarget
== n
&& bPutSeperator
)
200 iTarget
+= nNumberGroups
+ 1;
201 temp
[38 - n
++] = cThousandSeparator
;
203 temp
[38 - n
++] = (TCHAR
)(num
% 10) + _T('0');
209 memcpy(des
, temp
+ 39 - n
, n
* sizeof(TCHAR
));
216 * Is a process a console process?
218 static BOOL
IsConsoleProcess(HANDLE Process
)
221 PROCESS_BASIC_INFORMATION Info
;
225 if (NULL
== NtQueryInformationProcessPtr
|| NULL
== NtReadVirtualMemoryPtr
)
230 Status
= NtQueryInformationProcessPtr (
231 Process
, ProcessBasicInformation
,
232 &Info
, sizeof(PROCESS_BASIC_INFORMATION
), NULL
);
233 if (! NT_SUCCESS(Status
))
235 WARN ("NtQueryInformationProcess failed with status %08x\n", Status
);
238 Status
= NtReadVirtualMemoryPtr (
239 Process
, Info
.PebBaseAddress
, &ProcessPeb
,
240 sizeof(PEB
), &BytesRead
);
241 if (! NT_SUCCESS(Status
) || sizeof(PEB
) != BytesRead
)
243 WARN ("Couldn't read virt mem status %08x bytes read %lu\n", Status
, BytesRead
);
247 return IMAGE_SUBSYSTEM_WINDOWS_CUI
== ProcessPeb
.ImageSubSystem
;
253 #define SHELLEXECUTETEXT "ShellExecuteExW"
255 #define SHELLEXECUTETEXT "ShellExecuteExA"
258 typedef BOOL (WINAPI
*MYEX
)(LPSHELLEXECUTEINFO lpExecInfo
);
260 HANDLE
RunFile(DWORD flags
, LPTSTR filename
, LPTSTR params
,
261 LPTSTR directory
, INT show
)
263 SHELLEXECUTEINFO sei
;
268 TRACE ("RunFile(%s)\n", debugstr_aw(filename
));
269 hShell32
= LoadLibrary(_T("SHELL32.DLL"));
272 WARN ("RunFile: couldn't load SHELL32.DLL!\n");
276 hShExt
= (MYEX
)(FARPROC
)GetProcAddress(hShell32
, SHELLEXECUTETEXT
);
279 WARN ("RunFile: couldn't find ShellExecuteExA/W in SHELL32.DLL!\n");
280 FreeLibrary(hShell32
);
284 TRACE ("RunFile: ShellExecuteExA/W is at %x\n", hShExt
);
286 memset(&sei
, 0, sizeof sei
);
287 sei
.cbSize
= sizeof sei
;
289 sei
.lpFile
= filename
;
290 sei
.lpParameters
= params
;
291 sei
.lpDirectory
= directory
;
295 TRACE ("RunFile: ShellExecuteExA/W returned 0x%p\n", ret
);
297 FreeLibrary(hShell32
);
298 return ret
? sei
.hProcess
: NULL
;
304 * This command (in first) was not found in the command table
306 * Full - buffer to hold whole command line
307 * First - first word on command line
308 * Rest - rest of command line
312 Execute (LPTSTR Full
, LPTSTR First
, LPTSTR Rest
, PARSED_COMMAND
*Cmd
)
314 TCHAR szFullName
[MAX_PATH
];
315 TCHAR
*first
, *rest
, *dot
;
316 TCHAR szWindowTitle
[MAX_PATH
];
317 DWORD dwExitCode
= 0;
320 TRACE ("Execute: \'%s\' \'%s\'\n", debugstr_aw(First
), debugstr_aw(Rest
));
322 /* Though it was already parsed once, we have a different set of rules
323 for parsing before we pass to CreateProccess */
324 if (First
[0] == _T('/') || (First
[0] && First
[1] == _T(':')))
326 /* Use the entire first word as the program name (no change) */
327 FirstEnd
= First
+ _tcslen(First
);
331 /* If present in the first word, spaces and ,;=/ end the program
332 * name and become the beginning of its parameters. */
333 BOOL bInside
= FALSE
;
334 for (FirstEnd
= First
; *FirstEnd
; FirstEnd
++)
336 if (!bInside
&& (_istspace(*FirstEnd
) || _tcschr(_T(",;=/"), *FirstEnd
)))
338 bInside
^= *FirstEnd
== _T('"');
342 /* Copy the new first/rest into the buffer */
344 rest
= &Full
[FirstEnd
- First
+ 1];
345 _tcscpy(rest
, FirstEnd
);
347 *FirstEnd
= _T('\0');
348 _tcscpy(first
, First
);
350 /* check for a drive change */
351 if ((_istalpha (first
[0])) && (!_tcscmp (first
+ 1, _T(":"))))
354 if (!SetCurrentDirectory(first
))
355 /* Guess they changed disc or something, handle that gracefully and get to root */
362 working
= SetCurrentDirectory(str
);
365 if (!working
) ConErrResPuts (STRING_FREE_ERROR1
);
369 /* get the PATH environment variable and parse it */
370 /* search the PATH environment variable for the binary */
372 if (!SearchForExecutable(First
, szFullName
))
374 error_bad_command(first
);
378 GetConsoleTitle (szWindowTitle
, MAX_PATH
);
380 /* check if this is a .BAT or .CMD file */
381 dot
= _tcsrchr (szFullName
, _T('.'));
382 if (dot
&& (!_tcsicmp (dot
, _T(".bat")) || !_tcsicmp (dot
, _T(".cmd"))))
384 while (*rest
== _T(' '))
386 TRACE ("[BATCH: %s %s]\n", debugstr_aw(szFullName
), debugstr_aw(rest
));
387 dwExitCode
= Batch(szFullName
, first
, rest
, Cmd
);
391 /* exec the program */
392 PROCESS_INFORMATION prci
;
395 /* build command line for CreateProcess(): first + " " + rest */
399 TRACE ("[EXEC: %s]\n", debugstr_aw(Full
));
401 /* fill startup info */
402 memset (&stui
, 0, sizeof (STARTUPINFO
));
403 stui
.cb
= sizeof (STARTUPINFO
);
404 stui
.dwFlags
= STARTF_USESHOWWINDOW
;
405 stui
.wShowWindow
= SW_SHOWDEFAULT
;
407 // return console to standard mode
408 SetConsoleMode (GetStdHandle(STD_INPUT_HANDLE
),
409 ENABLE_LINE_INPUT
| ENABLE_PROCESSED_INPUT
| ENABLE_ECHO_INPUT
);
411 if (CreateProcess (szFullName
,
416 0, /* CREATE_NEW_PROCESS_GROUP */
423 CloseHandle(prci
.hThread
);
427 // See if we can run this with ShellExecute() ie myfile.xls
428 prci
.hProcess
= RunFile(SEE_MASK_NOCLOSEPROCESS
| SEE_MASK_NO_CONSOLE
,
435 if (prci
.hProcess
!= NULL
)
437 if (IsConsoleProcess(prci
.hProcess
))
439 /* FIXME: Protect this with critical section */
440 bChildProcessRunning
= TRUE
;
441 dwChildProcessId
= prci
.dwProcessId
;
443 WaitForSingleObject (prci
.hProcess
, INFINITE
);
445 /* FIXME: Protect this with critical section */
446 bChildProcessRunning
= FALSE
;
448 GetExitCodeProcess (prci
.hProcess
, &dwExitCode
);
449 nErrorLevel
= (INT
)dwExitCode
;
451 CloseHandle (prci
.hProcess
);
455 TRACE ("[ShellExecute failed!: %s]\n", debugstr_aw(Full
));
456 error_bad_command (first
);
460 // restore console mode
462 GetStdHandle( STD_INPUT_HANDLE
),
463 ENABLE_PROCESSED_INPUT
);
466 /* Get code page if it has been change */
467 InputCodePage
= GetConsoleCP();
468 OutputCodePage
= GetConsoleOutputCP();
469 SetConsoleTitle (szWindowTitle
);
476 * look through the internal commands and determine whether or not this
477 * command is one of them. If it is, call the command. If not, call
478 * execute to run it as an external program.
480 * first - first word on command line
481 * rest - rest of command line
485 DoCommand(LPTSTR first
, LPTSTR rest
, PARSED_COMMAND
*Cmd
)
489 LPTSTR param
; /* pointer to command's parameters */
492 BOOL nointernal
= FALSE
;
495 TRACE ("DoCommand: (\'%s\' \'%s\')\n", debugstr_aw(first
), debugstr_aw(rest
));
497 /* full command line */
498 com
= cmd_alloc((_tcslen(first
) + _tcslen(rest
) + 2) * sizeof(TCHAR
));
501 error_out_of_memory();
505 /* If present in the first word, these characters end the name of an
506 * internal command and become the beginning of its parameters. */
507 cp
= first
+ _tcscspn(first
, _T("\t +,/;=[]"));
509 for (cl
= 0; cl
< (cp
- first
); cl
++)
511 /* These characters do it too, but if one of them is present,
512 * then we check to see if the word is a file name and skip
513 * checking for internal commands if so.
514 * This allows running programs with names like "echo.exe" */
515 if (_tcschr(_T(".:\\"), first
[cl
]))
519 nointernal
= IsExistingFile(first
);
525 /* Scan internal command table */
526 for (cmdptr
= cmds
; !nointernal
&& cmdptr
->name
; cmdptr
++)
528 if (!_tcsnicmp(first
, cmdptr
->name
, cl
) && cmdptr
->name
[cl
] == _T('\0'))
534 /* Skip over whitespace to rest of line, exclude 'echo' command */
535 if (_tcsicmp(cmdptr
->name
, _T("echo")) != 0)
536 while (_istspace(*param
))
538 ret
= cmdptr
->func(param
);
544 ret
= Execute(com
, first
, rest
, Cmd
);
551 * process the command line and execute the appropriate functions
552 * full input/output redirection and piping are supported
555 INT
ParseCommandLine (LPTSTR cmd
)
558 PARSED_COMMAND
*Cmd
= ParseCommand(cmd
);
561 Ret
= ExecuteCommand(Cmd
);
567 /* Execute a command without waiting for it to finish. If it's an internal
568 * command or batch file, we must create a new cmd.exe process to handle it.
569 * TODO: For now, this just always creates a cmd.exe process.
570 * This works, but is inefficient for running external programs,
571 * which could just be run directly. */
573 ExecuteAsync(PARSED_COMMAND
*Cmd
)
575 TCHAR CmdPath
[MAX_PATH
];
576 TCHAR CmdParams
[CMDLINE_LENGTH
], *ParamsEnd
;
578 PROCESS_INFORMATION prci
;
580 /* Get the path to cmd.exe */
581 GetModuleFileName(NULL
, CmdPath
, MAX_PATH
);
583 /* Build the parameter string to pass to cmd.exe */
584 ParamsEnd
= _stpcpy(CmdParams
, _T("/S/D/C\""));
585 ParamsEnd
= Unparse(Cmd
, ParamsEnd
, &CmdParams
[CMDLINE_LENGTH
- 2]);
588 error_out_of_memory();
591 _tcscpy(ParamsEnd
, _T("\""));
593 memset(&stui
, 0, sizeof stui
);
594 stui
.cb
= sizeof(STARTUPINFO
);
595 if (!CreateProcess(CmdPath
, CmdParams
, NULL
, NULL
, TRUE
, 0,
596 NULL
, NULL
, &stui
, &prci
))
598 ErrorMessage(GetLastError(), NULL
);
602 CloseHandle(prci
.hThread
);
603 return prci
.hProcess
;
607 ExecutePipeline(PARSED_COMMAND
*Cmd
)
609 #ifdef FEATURE_REDIRECTION
610 HANDLE hInput
= NULL
;
611 HANDLE hOldConIn
= GetStdHandle(STD_INPUT_HANDLE
);
612 HANDLE hOldConOut
= GetStdHandle(STD_OUTPUT_HANDLE
);
613 HANDLE hProcess
[MAXIMUM_WAIT_OBJECTS
];
617 /* Do all but the last pipe command */
620 HANDLE hPipeRead
, hPipeWrite
;
621 if (nProcesses
> (MAXIMUM_WAIT_OBJECTS
- 2))
623 error_too_many_parameters(_T("|"));
627 /* Create the pipe that this process will write into.
628 * Make the handles non-inheritable initially, because this
629 * process shouldn't inherit the reading handle. */
630 if (!CreatePipe(&hPipeRead
, &hPipeWrite
, NULL
, 0))
636 /* The writing side of the pipe is STDOUT for this process */
637 SetHandleInformation(hPipeWrite
, HANDLE_FLAG_INHERIT
, HANDLE_FLAG_INHERIT
);
638 SetStdHandle(STD_OUTPUT_HANDLE
, hPipeWrite
);
640 /* Execute it (error check is done later for easier cleanup) */
641 hProcess
[nProcesses
] = ExecuteAsync(Cmd
->Subcommands
);
642 CloseHandle(hPipeWrite
);
646 /* The reading side of the pipe will be STDIN for the next process */
647 SetHandleInformation(hPipeRead
, HANDLE_FLAG_INHERIT
, HANDLE_FLAG_INHERIT
);
648 SetStdHandle(STD_INPUT_HANDLE
, hPipeRead
);
651 if (!hProcess
[nProcesses
])
655 Cmd
= Cmd
->Subcommands
->Next
;
656 } while (Cmd
->Type
== C_PIPE
);
658 /* The last process uses the original STDOUT */
659 SetStdHandle(STD_OUTPUT_HANDLE
, hOldConOut
);
660 hProcess
[nProcesses
] = ExecuteAsync(Cmd
);
661 if (!hProcess
[nProcesses
])
665 SetStdHandle(STD_INPUT_HANDLE
, hOldConIn
);
667 /* Wait for all processes to complete */
668 bChildProcessRunning
= TRUE
;
669 WaitForMultipleObjects(nProcesses
, hProcess
, TRUE
, INFINITE
);
670 bChildProcessRunning
= FALSE
;
672 /* Use the exit code of the last process in the pipeline */
673 GetExitCodeProcess(hProcess
[nProcesses
- 1], &dwExitCode
);
674 nErrorLevel
= (INT
)dwExitCode
;
676 while (--nProcesses
>= 0)
677 CloseHandle(hProcess
[nProcesses
]);
683 while (--nProcesses
>= 0)
685 TerminateProcess(hProcess
[nProcesses
], 0);
686 CloseHandle(hProcess
[nProcesses
]);
688 SetStdHandle(STD_INPUT_HANDLE
, hOldConIn
);
689 SetStdHandle(STD_OUTPUT_HANDLE
, hOldConOut
);
694 ExecuteCommand(PARSED_COMMAND
*Cmd
)
700 if (!PerformRedirection(Cmd
->Redirections
))
707 First
= DoDelayedExpansion(Cmd
->Command
.First
);
710 Rest
= DoDelayedExpansion(Cmd
->Command
.Rest
);
713 Ret
= DoCommand(First
, Rest
, Cmd
);
722 for (Sub
= Cmd
->Subcommands
; Sub
; Sub
= Sub
->Next
)
723 Ret
= ExecuteCommand(Sub
);
726 Sub
= Cmd
->Subcommands
;
727 Ret
= ExecuteCommand(Sub
);
731 Ret
= ExecuteCommand(Sub
->Next
);
735 Sub
= Cmd
->Subcommands
;
736 Ret
= ExecuteCommand(Sub
);
738 Ret
= ExecuteCommand(Sub
->Next
);
741 ExecutePipeline(Cmd
);
744 Ret
= ExecuteIf(Cmd
);
747 Ret
= ExecuteFor(Cmd
);
751 UndoRedirection(Cmd
->Redirections
, NULL
);
756 GetEnvVar(LPCTSTR varName
)
758 static LPTSTR ret
= NULL
;
763 size
= GetEnvironmentVariable(varName
, NULL
, 0);
766 ret
= cmd_alloc(size
* sizeof(TCHAR
));
768 GetEnvironmentVariable(varName
, ret
, size
+ 1);
774 GetEnvVarOrSpecial(LPCTSTR varName
)
776 static TCHAR ret
[MAX_PATH
];
778 LPTSTR var
= GetEnvVar(varName
);
782 /* env var doesn't exist, look for a "special" one */
784 if (_tcsicmp(varName
,_T("cd")) ==0)
786 GetCurrentDirectory(MAX_PATH
, ret
);
790 else if (_tcsicmp(varName
,_T("time")) ==0)
792 return GetTimeString();
795 else if (_tcsicmp(varName
,_T("date")) ==0)
797 return GetDateString();
801 else if (_tcsicmp(varName
,_T("random")) ==0)
803 /* Get random number */
804 _itot(rand(),ret
,10);
809 else if (_tcsicmp(varName
,_T("cmdcmdline")) ==0)
811 return GetCommandLine();
814 /* %CMDEXTVERSION% */
815 else if (_tcsicmp(varName
,_T("cmdextversion")) ==0)
817 /* Set version number to 2 */
823 else if (_tcsicmp(varName
,_T("errorlevel")) ==0)
825 _itot(nErrorLevel
,ret
,10);
832 /* Handle the %~var syntax */
834 GetEnhancedVar(TCHAR
**pFormat
, LPTSTR (*GetVar
)(TCHAR
, BOOL
*))
836 static const TCHAR ModifierTable
[] = _T("dpnxfsatz");
838 M_DRIVE
= 1, /* D: drive letter */
839 M_PATH
= 2, /* P: path */
840 M_NAME
= 4, /* N: filename */
841 M_EXT
= 8, /* X: extension */
842 M_FULL
= 16, /* F: full path (drive+path+name+ext) */
843 M_SHORT
= 32, /* S: full path (drive+path+name+ext), use short names */
844 M_ATTR
= 64, /* A: attributes */
845 M_TIME
= 128, /* T: modification time */
846 M_SIZE
= 256, /* Z: file size */
849 TCHAR
*Format
, *FormatEnd
;
850 TCHAR
*PathVarName
= NULL
;
853 BOOL VariableIsParam0
;
854 TCHAR FullPath
[MAX_PATH
];
855 TCHAR FixedPath
[MAX_PATH
], *Filename
, *Extension
;
857 WIN32_FIND_DATA w32fd
;
860 static TCHAR Result
[CMDLINE_LENGTH
];
862 /* There is ambiguity between modifier characters and FOR variables;
863 * the rule that cmd uses is to pick the longest possible match.
864 * For example, if there is a %n variable, then out of %~anxnd,
865 * %~anxn will be substituted rather than just %~an. */
867 /* First, go through as many modifier characters as possible */
868 FormatEnd
= Format
= *pFormat
;
869 while (*FormatEnd
&& _tcschr(ModifierTable
, _totlower(*FormatEnd
)))
872 if (*FormatEnd
== _T('$'))
875 PathVarName
= FormatEnd
+ 1;
876 FormatEnd
= _tcschr(PathVarName
, _T(':'));
880 /* Must be immediately followed by the variable */
881 Variable
= GetVar(*++FormatEnd
, &VariableIsParam0
);
887 /* Backtrack if necessary to get a variable name match */
888 while (!(Variable
= GetVar(*FormatEnd
, &VariableIsParam0
)))
890 if (FormatEnd
== Format
)
896 for (; Format
< FormatEnd
&& *Format
!= _T('$'); Format
++)
897 Modifiers
|= 1 << (_tcschr(ModifierTable
, _totlower(*Format
)) - ModifierTable
);
899 *pFormat
= FormatEnd
+ 1;
901 /* Exclude the leading and trailing quotes */
902 VarEnd
= &Variable
[_tcslen(Variable
)];
903 if (*Variable
== _T('"'))
906 if (VarEnd
> Variable
&& VarEnd
[-1] == _T('"'))
910 if ((char *)VarEnd
- (char *)Variable
>= sizeof Result
)
912 memcpy(Result
, Variable
, (char *)VarEnd
- (char *)Variable
);
913 Result
[VarEnd
- Variable
] = _T('\0');
917 /* $PATH: syntax - search the directories listed in the
918 * specified environment variable for the file */
920 FormatEnd
[-1] = _T('\0');
921 PathVar
= GetEnvVar(PathVarName
);
922 FormatEnd
[-1] = _T(':');
924 !SearchPath(PathVar
, Result
, NULL
, MAX_PATH
, FullPath
, NULL
))
929 else if (Modifiers
== 0)
931 /* For plain %~var with no modifiers, just return the variable without quotes */
934 else if (VariableIsParam0
)
936 /* Special case: If the variable is %0 and modifier characters are present,
937 * use the batch file's path (which includes the .bat/.cmd extension)
938 * rather than the actual %0 variable (which might not). */
939 _tcscpy(FullPath
, bc
->BatchFilePath
);
943 /* Convert the variable, now without quotes, to a full path */
944 if (!GetFullPathName(Result
, MAX_PATH
, FullPath
, NULL
))
948 /* Next step is to change the path to fix letter case (e.g.
949 * C:\ReAcToS -> C:\ReactOS) and, if requested with the S modifier,
950 * replace long filenames with short. */
955 /* Copy drive letter */
959 /* Loop over each \-separated component in the path */
961 TCHAR
*Next
= _tcschr(In
, _T('\\'));
964 /* Use FindFirstFile to get the correct name */
965 if (Out
+ _tcslen(In
) + 1 >= &FixedPath
[MAX_PATH
])
968 hFind
= FindFirstFile(FixedPath
, &w32fd
);
969 /* If it doesn't exist, just leave the name as it was given */
970 if (hFind
!= INVALID_HANDLE_VALUE
)
972 LPTSTR FixedComponent
= w32fd
.cFileName
;
973 if (*w32fd
.cAlternateFileName
&&
974 ((Modifiers
& M_SHORT
) || !_tcsicmp(In
, w32fd
.cAlternateFileName
)))
976 FixedComponent
= w32fd
.cAlternateFileName
;
980 if (Out
+ _tcslen(FixedComponent
) + 1 >= &FixedPath
[MAX_PATH
])
982 _tcscpy(Out
, FixedComponent
);
989 } while (In
!= NULL
);
992 /* Build the result string. Start with attributes, modification time, and
993 * file size. If the file didn't exist, these fields will all be empty. */
995 if (hFind
!= INVALID_HANDLE_VALUE
)
997 if (Modifiers
& M_ATTR
)
999 static const struct {
1002 } *Attrib
, Table
[] = {
1003 { _T('d'), FILE_ATTRIBUTE_DIRECTORY
},
1004 { _T('r'), FILE_ATTRIBUTE_READONLY
},
1005 { _T('a'), FILE_ATTRIBUTE_ARCHIVE
},
1006 { _T('h'), FILE_ATTRIBUTE_HIDDEN
},
1007 { _T('s'), FILE_ATTRIBUTE_SYSTEM
},
1008 { _T('c'), FILE_ATTRIBUTE_COMPRESSED
},
1009 { _T('o'), FILE_ATTRIBUTE_OFFLINE
},
1010 { _T('t'), FILE_ATTRIBUTE_TEMPORARY
},
1011 { _T('l'), FILE_ATTRIBUTE_REPARSE_POINT
},
1013 for (Attrib
= Table
; Attrib
!= &Table
[9]; Attrib
++)
1015 *Out
++ = w32fd
.dwFileAttributes
& Attrib
->Value
1021 if (Modifiers
& M_TIME
)
1025 FileTimeToLocalFileTime(&w32fd
.ftLastWriteTime
, &ft
);
1026 FileTimeToSystemTime(&ft
, &st
);
1028 Out
+= FormatDate(Out
, &st
, TRUE
);
1030 Out
+= FormatTime(Out
, &st
);
1033 if (Modifiers
& M_SIZE
)
1035 ULARGE_INTEGER Size
;
1036 Size
.LowPart
= w32fd
.nFileSizeLow
;
1037 Size
.HighPart
= w32fd
.nFileSizeHigh
;
1038 Out
+= _stprintf(Out
, _T("%I64u "), Size
.QuadPart
);
1042 /* When using the path-searching syntax or the S modifier,
1043 * at least part of the file path is always included.
1044 * If none of the DPNX modifiers are present, include the full path */
1045 if (PathVarName
|| (Modifiers
& M_SHORT
))
1046 if ((Modifiers
& (M_DRIVE
| M_PATH
| M_NAME
| M_EXT
)) == 0)
1047 Modifiers
|= M_FULL
;
1049 /* Now add the requested parts of the name.
1050 * With the F modifier, add all parts to form the full path. */
1051 Extension
= _tcsrchr(Filename
, _T('.'));
1052 if (Modifiers
& (M_DRIVE
| M_FULL
))
1054 *Out
++ = FixedPath
[0];
1055 *Out
++ = FixedPath
[1];
1057 if (Modifiers
& (M_PATH
| M_FULL
))
1059 memcpy(Out
, &FixedPath
[2], (char *)Filename
- (char *)&FixedPath
[2]);
1060 Out
+= Filename
- &FixedPath
[2];
1062 if (Modifiers
& (M_NAME
| M_FULL
))
1064 while (*Filename
&& Filename
!= Extension
)
1065 *Out
++ = *Filename
++;
1067 if (Modifiers
& (M_EXT
| M_FULL
))
1070 Out
= _stpcpy(Out
, Extension
);
1073 /* Trim trailing space which otherwise would appear as a
1074 * result of using the A/T/Z modifiers but no others. */
1075 while (Out
!= &Result
[0] && Out
[-1] == _T(' '))
1083 GetBatchVar(TCHAR
*varName
, UINT
*varNameLen
)
1094 varNameEnd
= varName
+ 1;
1095 ret
= GetEnhancedVar(&varNameEnd
, FindArg
);
1098 error_syntax(varName
);
1101 *varNameLen
= varNameEnd
- varName
;
1113 return FindArg(*varName
, &dummy
);
1117 // Copy over the raw params(not including the batch file name
1119 return bc
->raw_params
;
1128 SubstituteVars(TCHAR
*Src
, TCHAR
*Dest
, TCHAR Delim
)
1130 #define APPEND(From, Length) { \
1131 if (Dest + (Length) > DestEnd) \
1133 memcpy(Dest, From, (Length) * sizeof(TCHAR)); \
1135 #define APPEND1(Char) { \
1136 if (Dest >= DestEnd) \
1140 TCHAR
*DestEnd
= Dest
+ CMDLINE_LENGTH
- 1;
1154 if (bc
&& Delim
== _T('%'))
1157 Var
= GetBatchVar(Src
, &NameLen
);
1160 VarLength
= _tcslen(Var
);
1161 APPEND(Var
, VarLength
)
1167 /* Find the end of the variable name. A colon (:) will usually
1168 * end the name and begin the optional modifier, but not if it
1169 * is immediately followed by the delimiter (%VAR:%). */
1171 while (*Src
!= Delim
&& !(*Src
== _T(':') && Src
[1] != Delim
))
1180 Var
= GetEnvVarOrSpecial(SubstStart
);
1184 /* In a batch file, %NONEXISTENT% "expands" to an empty string */
1189 VarLength
= _tcslen(Var
);
1191 if (EndChr
== Delim
)
1193 /* %VAR% - use as-is */
1194 APPEND(Var
, VarLength
)
1196 else if (*Src
== _T('~'))
1198 /* %VAR:~[start][,length]% - substring
1199 * Negative values are offsets from the end */
1200 int Start
= _tcstol(Src
+ 1, &Src
, 0);
1201 int End
= VarLength
;
1204 Start
= max(Start
, 0);
1205 Start
= min(Start
, VarLength
);
1206 if (*Src
== _T(','))
1208 End
= _tcstol(Src
+ 1, &Src
, 0);
1209 End
+= (End
< 0) ? VarLength
: Start
;
1210 End
= max(End
, Start
);
1211 End
= min(End
, VarLength
);
1213 if (*Src
++ != Delim
)
1215 APPEND(&Var
[Start
], End
- Start
);
1219 /* %VAR:old=new% - replace all occurrences of old with new
1220 * %VAR:*old=new% - replace first occurrence only,
1221 * and remove everything before it */
1223 DWORD OldLength
, NewLength
;
1225 int LastMatch
= 0, i
= 0;
1227 if (*Src
== _T('*'))
1233 /* the string to replace may contain the delimiter */
1234 Src
= _tcschr(Old
= Src
, _T('='));
1237 OldLength
= Src
++ - Old
;
1241 Src
= _tcschr(New
= Src
, Delim
);
1244 NewLength
= Src
++ - New
;
1246 while (i
< VarLength
)
1248 if (_tcsnicmp(&Var
[i
], Old
, OldLength
) == 0)
1251 APPEND(&Var
[LastMatch
], i
- LastMatch
)
1252 APPEND(New
, NewLength
)
1261 APPEND(&Var
[LastMatch
], VarLength
- LastMatch
)
1273 ConOutResPrintf(STRING_ALIAS_ERROR
);
1280 /* Search the list of FOR contexts for a variable */
1281 static LPTSTR
FindForVar(TCHAR Var
, BOOL
*IsParam0
)
1285 for (Ctx
= fc
; Ctx
!= NULL
; Ctx
= Ctx
->prev
)
1286 if ((UINT
)(Var
- Ctx
->firstvar
) < Ctx
->varcount
)
1287 return Ctx
->values
[Var
- Ctx
->firstvar
];
1292 SubstituteForVars(TCHAR
*Src
, TCHAR
*Dest
)
1294 TCHAR
*DestEnd
= &Dest
[CMDLINE_LENGTH
- 1];
1297 if (Src
[0] == _T('%'))
1300 LPTSTR End
= &Src
[2];
1301 LPTSTR Value
= NULL
;
1303 if (Src
[1] == _T('~'))
1304 Value
= GetEnhancedVar(&End
, FindForVar
);
1307 Value
= FindForVar(Src
[1], &Dummy
);
1311 if (Dest
+ _tcslen(Value
) > DestEnd
)
1313 Dest
= _stpcpy(Dest
, Value
);
1318 /* Not a variable; just copy the character */
1319 if (Dest
>= DestEnd
)
1328 DoDelayedExpansion(LPTSTR Line
)
1330 TCHAR Buf1
[CMDLINE_LENGTH
];
1331 TCHAR Buf2
[CMDLINE_LENGTH
];
1333 /* First, substitute FOR variables */
1334 if (!SubstituteForVars(Line
, Buf1
))
1337 if (!bDelayedExpansion
|| !_tcschr(Buf1
, _T('!')))
1338 return cmd_dup(Buf1
);
1340 /* FIXME: Delayed substitutions actually aren't quite the same as
1341 * immediate substitutions. In particular, it's possible to escape
1342 * the exclamation point using ^. */
1343 if (!SubstituteVars(Buf1
, Buf2
, _T('!')))
1345 return cmd_dup(Buf2
);
1350 * do the prompt/input/process loop
1355 ReadLine (TCHAR
*commandline
, BOOL bMore
)
1357 TCHAR readline
[CMDLINE_LENGTH
];
1360 /* if no batch input then... */
1365 ConOutResPrintf(STRING_MORE
);
1369 /* JPP 19980807 - if echo off, don't print prompt */
1378 if (!ReadCommand(readline
, CMDLINE_LENGTH
- 1))
1384 if (CheckCtrlBreak(BREAK_INPUT
))
1386 ConOutPuts(_T("\n"));
1393 ip
= ReadBatchLine();
1398 return SubstituteVars(ip
, commandline
, _T('%'));
1404 PARSED_COMMAND
*Cmd
;
1406 while (!bCanExit
|| !bExit
)
1408 Cmd
= ParseCommand(NULL
);
1412 ExecuteCommand(Cmd
);
1419 * control-break handler.
1421 BOOL WINAPI
BreakHandler (DWORD dwCtrlType
)
1426 static BOOL SelfGenerated
= FALSE
;
1428 if ((dwCtrlType
!= CTRL_C_EVENT
) &&
1429 (dwCtrlType
!= CTRL_BREAK_EVENT
))
1437 SelfGenerated
= FALSE
;
1442 if (bChildProcessRunning
== TRUE
)
1444 SelfGenerated
= TRUE
;
1445 GenerateConsoleCtrlEvent (dwCtrlType
, 0);
1450 rec
.EventType
= KEY_EVENT
;
1451 rec
.Event
.KeyEvent
.bKeyDown
= TRUE
;
1452 rec
.Event
.KeyEvent
.wRepeatCount
= 1;
1453 rec
.Event
.KeyEvent
.wVirtualKeyCode
= _T('C');
1454 rec
.Event
.KeyEvent
.wVirtualScanCode
= _T('C') - 35;
1455 rec
.Event
.KeyEvent
.uChar
.AsciiChar
= _T('C');
1456 rec
.Event
.KeyEvent
.uChar
.UnicodeChar
= _T('C');
1457 rec
.Event
.KeyEvent
.dwControlKeyState
= RIGHT_CTRL_PRESSED
;
1466 /* FIXME: Handle batch files */
1468 //ConOutPrintf(_T("^C"));
1475 VOID
AddBreakHandler (VOID
)
1477 SetConsoleCtrlHandler ((PHANDLER_ROUTINE
)BreakHandler
, TRUE
);
1481 VOID
RemoveBreakHandler (VOID
)
1483 SetConsoleCtrlHandler ((PHANDLER_ROUTINE
)BreakHandler
, FALSE
);
1488 * show commands and options that are available.
1495 /* print command list */
1496 ConOutResPuts(STRING_CMD_HELP1
);
1499 /* print feature list */
1500 ConOutResPuts(STRING_CMD_HELP2
);
1502 #ifdef FEATURE_ALIASES
1503 ConOutResPuts(STRING_CMD_HELP3
);
1505 #ifdef FEATURE_HISTORY
1506 ConOutResPuts(STRING_CMD_HELP4
);
1508 #ifdef FEATURE_UNIX_FILENAME_COMPLETION
1509 ConOutResPuts(STRING_CMD_HELP5
);
1511 #ifdef FEATURE_DIRECTORY_STACK
1512 ConOutResPuts(STRING_CMD_HELP6
);
1514 #ifdef FEATURE_REDIRECTION
1515 ConOutResPuts(STRING_CMD_HELP7
);
1517 ConOutChar(_T('\n'));
1522 ExecuteAutoRunFile(HKEY hkeyRoot
)
1524 TCHAR autorun
[2048];
1525 DWORD len
= sizeof autorun
;
1528 if (RegOpenKeyEx(hkeyRoot
,
1529 _T("SOFTWARE\\Microsoft\\Command Processor"),
1532 &hkey
) == ERROR_SUCCESS
)
1534 if(RegQueryValueEx(hkey
,
1539 &len
) == ERROR_SUCCESS
)
1542 ParseCommandLine(autorun
);
1548 /* Get the command that comes after a /C or /K switch */
1550 GetCmdLineCommand(TCHAR
*commandline
, TCHAR
*ptr
, BOOL AlwaysStrip
)
1554 while (_istspace(*ptr
))
1557 /* Remove leading quote, find final quote */
1558 if (*ptr
== _T('"') &&
1559 (LastQuote
= _tcsrchr(++ptr
, _T('"'))) != NULL
)
1562 /* Under certain circumstances, all quotes are preserved.
1563 * CMD /? documents these conditions as follows:
1565 * 2. Exactly two quotes
1566 * 3. No "special characters" between the quotes
1567 * (CMD /? says &<>()@^| but parentheses did not
1568 * trigger this rule when I tested them.)
1569 * 4. Whitespace exists between the quotes
1570 * 5. Enclosed string is an executable filename
1572 *LastQuote
= _T('\0');
1573 for (Space
= ptr
+ 1; Space
< LastQuote
; Space
++)
1575 if (_istspace(*Space
)) /* Rule 4 */
1577 if (!AlwaysStrip
&& /* Rule 1 */
1578 !_tcspbrk(ptr
, _T("\"&<>@^|")) && /* Rules 2, 3 */
1579 SearchForExecutable(ptr
, commandline
)) /* Rule 5 */
1581 /* All conditions met: preserve both the quotes */
1582 *LastQuote
= _T('"');
1583 _tcscpy(commandline
, ptr
- 1);
1590 /* The conditions were not met: remove both the
1591 * leading quote and the last quote */
1592 _tcscpy(commandline
, ptr
);
1593 _tcscpy(&commandline
[LastQuote
- ptr
], LastQuote
+ 1);
1597 /* No quotes; just copy */
1598 _tcscpy(commandline
, ptr
);
1602 * set up global initializations and process parameters
1607 HMODULE NtDllModule
;
1608 TCHAR commandline
[CMDLINE_LENGTH
];
1609 TCHAR ModuleName
[_MAX_PATH
+ 1];
1614 TCHAR
*ptr
, *cmdLine
, option
= 0;
1615 BOOL AlwaysStrip
= FALSE
;
1616 BOOL AutoRun
= TRUE
;
1618 /* get version information */
1619 osvi
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
1620 GetVersionEx (&osvi
);
1622 /* Some people like to run ReactOS cmd.exe on Win98, it helps in the
1623 * build process. So don't link implicitly against ntdll.dll, load it
1624 * dynamically instead */
1625 NtDllModule
= GetModuleHandle(TEXT("ntdll.dll"));
1626 if (NtDllModule
!= NULL
)
1628 NtQueryInformationProcessPtr
= (NtQueryInformationProcessProc
)GetProcAddress(NtDllModule
, "NtQueryInformationProcess");
1629 NtReadVirtualMemoryPtr
= (NtReadVirtualMemoryProc
)GetProcAddress(NtDllModule
, "NtReadVirtualMemory");
1634 /* get default input and output console handles */
1635 hOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
1636 hIn
= GetStdHandle (STD_INPUT_HANDLE
);
1638 /* Set EnvironmentVariable PROMPT if it does not exists any env value.
1639 for you can change the EnvirommentVariable for prompt before cmd start
1640 this patch are not 100% right, if it does not exists a PROMPT value cmd should use
1641 $P$G as defualt not set EnvirommentVariable PROMPT to $P$G if it does not exists */
1642 if (GetEnvironmentVariable(_T("PROMPT"),lpBuffer
, sizeof(lpBuffer
) / sizeof(lpBuffer
[0])) == 0)
1643 SetEnvironmentVariable (_T("PROMPT"), _T("$P$G"));
1645 #ifdef FEATURE_DIR_STACK
1646 /* initialize directory stack */
1647 InitDirectoryStack ();
1650 #ifdef FEATURE_HISTORY
1651 /*initialize history*/
1655 /* Set COMSPEC environment variable */
1656 if (0 != GetModuleFileName (NULL
, ModuleName
, _MAX_PATH
+ 1))
1658 ModuleName
[_MAX_PATH
] = _T('\0');
1659 SetEnvironmentVariable (_T("COMSPEC"), ModuleName
);
1662 /* add ctrl break handler */
1666 SetConsoleMode (hIn
, ENABLE_PROCESSED_INPUT
);
1668 cmdLine
= GetCommandLine();
1669 TRACE ("[command args: %s]\n", debugstr_aw(cmdLine
));
1671 for (ptr
= cmdLine
; *ptr
; ptr
++)
1673 if (*ptr
== _T('/'))
1675 option
= _totupper(ptr
[1]);
1676 if (option
== _T('?'))
1678 ConOutResPaging(TRUE
,STRING_CMD_HELP8
);
1683 else if (option
== _T('P'))
1685 if (!IsExistingFile (_T("\\autoexec.bat")))
1687 #ifdef INCLUDE_CMD_DATE
1690 #ifdef INCLUDE_CMD_TIME
1696 ParseCommandLine (_T("\\autoexec.bat"));
1700 else if (option
== _T('A'))
1702 bUnicodeOutput
= FALSE
;
1704 else if (option
== _T('C') || option
== _T('K') || option
== _T('R'))
1706 /* Remainder of command line is a command to be run */
1709 else if (option
== _T('D'))
1713 else if (option
== _T('Q'))
1715 bDisableBatchEcho
= TRUE
;
1717 else if (option
== _T('S'))
1721 #ifdef INCLUDE_CMD_COLOR
1722 else if (!_tcsnicmp(ptr
, _T("/T:"), 3))
1724 /* process /t (color) argument */
1725 wDefColor
= (WORD
)_tcstoul(&ptr
[3], &ptr
, 16);
1726 SetScreenColor(wDefColor
, TRUE
);
1729 else if (option
== _T('U'))
1731 bUnicodeOutput
= TRUE
;
1733 else if (option
== _T('V'))
1735 bDelayedExpansion
= _tcsnicmp(&ptr
[2], _T(":OFF"), 4);
1742 /* If neither /C or /K was given, display a simple version string */
1743 ConOutResPrintf(STRING_REACTOS_VERSION
,
1744 _T(KERNEL_RELEASE_STR
),
1745 _T(KERNEL_VERSION_BUILD_STR
));
1746 ConOutPuts(_T("(C) Copyright 1998-") _T(COPYRIGHT_YEAR
) _T(" ReactOS Team."));
1751 ExecuteAutoRunFile(HKEY_LOCAL_MACHINE
);
1752 ExecuteAutoRunFile(HKEY_CURRENT_USER
);
1757 /* Do the /C or /K command */
1758 GetCmdLineCommand(commandline
, &ptr
[2], AlwaysStrip
);
1759 nExitCode
= ParseCommandLine(commandline
);
1760 if (option
!= _T('K'))
1762 nErrorLevel
= nExitCode
;
1769 static VOID
Cleanup()
1771 /* run cmdexit.bat */
1772 if (IsExistingFile (_T("cmdexit.bat")))
1774 ConErrResPuts(STRING_CMD_ERROR5
);
1776 ParseCommandLine (_T("cmdexit.bat"));
1778 else if (IsExistingFile (_T("\\cmdexit.bat")))
1780 ConErrResPuts (STRING_CMD_ERROR5
);
1781 ParseCommandLine (_T("\\cmdexit.bat"));
1784 #ifdef FEATURE_DIECTORY_STACK
1785 /* destroy directory stack */
1786 DestroyDirectoryStack ();
1789 #ifdef FEATURE_HISTORY
1793 /* free GetEnvVar's buffer */
1796 /* remove ctrl break handler */
1797 RemoveBreakHandler ();
1798 SetConsoleMode( GetStdHandle( STD_INPUT_HANDLE
),
1799 ENABLE_LINE_INPUT
| ENABLE_PROCESSED_INPUT
| ENABLE_ECHO_INPUT
);
1805 int cmd_main (int argc
, const TCHAR
*argv
[])
1808 TCHAR startPath
[MAX_PATH
];
1809 CONSOLE_SCREEN_BUFFER_INFO Info
;
1811 lpOriginalEnvironment
= DuplicateEnvironment();
1813 GetCurrentDirectory(MAX_PATH
,startPath
);
1820 hConsole
= CreateFile(_T("CONOUT$"), GENERIC_READ
|GENERIC_WRITE
,
1821 FILE_SHARE_READ
|FILE_SHARE_WRITE
, NULL
,
1822 OPEN_EXISTING
, 0, NULL
);
1823 if (hConsole
!= INVALID_HANDLE_VALUE
)
1825 if (!GetConsoleScreenBufferInfo(hConsole
, &Info
))
1827 ConErrFormatMessage(GetLastError());
1830 wDefColor
= Info
.wAttributes
;
1831 CloseHandle(hConsole
);
1834 InputCodePage
= GetConsoleCP();
1835 OutputCodePage
= GetConsoleOutputCP();
1836 CMD_ModuleHandle
= GetModuleHandle(NULL
);
1838 /* check switches on command-line */
1841 /* call prompt routine */
1844 /* do the cleanup */
1847 cmd_free(lpOriginalEnvironment
);
1849 cmd_exit(nErrorLevel
);
1850 return(nErrorLevel
);