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
145 #include <reactos/buildno.h>
146 #include <reactos/version.h>
149 #define NT_SUCCESS(StatCode) ((NTSTATUS)(StatCode) >= 0)
152 typedef NTSTATUS (WINAPI
*NtQueryInformationProcessProc
)(HANDLE
, PROCESSINFOCLASS
,
153 PVOID
, ULONG
, PULONG
);
154 typedef NTSTATUS (WINAPI
*NtReadVirtualMemoryProc
)(HANDLE
, PVOID
, PVOID
, ULONG
, PULONG
);
156 BOOL bExit
= FALSE
; /* indicates EXIT was typed */
157 BOOL bCanExit
= TRUE
; /* indicates if this shell is exitable */
158 BOOL bCtrlBreak
= FALSE
; /* Ctrl-Break or Ctrl-C hit */
159 BOOL bIgnoreEcho
= FALSE
; /* Set this to TRUE to prevent a newline, when executing a command */
160 INT nErrorLevel
= 0; /* Errorlevel of last launched external program */
161 CRITICAL_SECTION ChildProcessRunningLock
;
162 BOOL bUnicodeOutput
= FALSE
;
163 BOOL bDisableBatchEcho
= FALSE
;
164 BOOL bDelayedExpansion
= FALSE
;
165 DWORD dwChildProcessId
= 0;
169 LPTSTR lpOriginalEnvironment
;
170 HANDLE CMD_ModuleHandle
;
172 static NtQueryInformationProcessProc NtQueryInformationProcessPtr
= NULL
;
173 static NtReadVirtualMemoryProc NtReadVirtualMemoryPtr
= NULL
;
175 #ifdef INCLUDE_CMD_COLOR
176 WORD wDefColor
; /* default color */
182 * insert commas into a number
185 ConvertULargeInteger(ULONGLONG num
, LPTSTR des
, UINT len
, BOOL bPutSeperator
)
187 TCHAR temp
[39]; /* maximum length with nNumberGroups == 1 */
194 iTarget
= nNumberGroups
;
196 bPutSeperator
= FALSE
;
200 if (iTarget
== n
&& bPutSeperator
)
202 iTarget
+= nNumberGroups
+ 1;
203 temp
[38 - n
++] = cThousandSeparator
;
205 temp
[38 - n
++] = (TCHAR
)(num
% 10) + _T('0');
211 memcpy(des
, temp
+ 39 - n
, n
* sizeof(TCHAR
));
218 * Is a process a console process?
220 static BOOL
IsConsoleProcess(HANDLE Process
)
223 PROCESS_BASIC_INFORMATION Info
;
227 if (NULL
== NtQueryInformationProcessPtr
|| NULL
== NtReadVirtualMemoryPtr
)
232 Status
= NtQueryInformationProcessPtr (
233 Process
, ProcessBasicInformation
,
234 &Info
, sizeof(PROCESS_BASIC_INFORMATION
), NULL
);
235 if (! NT_SUCCESS(Status
))
237 WARN ("NtQueryInformationProcess failed with status %08x\n", Status
);
240 Status
= NtReadVirtualMemoryPtr (
241 Process
, Info
.PebBaseAddress
, &ProcessPeb
,
242 sizeof(PEB
), &BytesRead
);
243 if (! NT_SUCCESS(Status
) || sizeof(PEB
) != BytesRead
)
245 WARN ("Couldn't read virt mem status %08x bytes read %lu\n", Status
, BytesRead
);
249 return IMAGE_SUBSYSTEM_WINDOWS_CUI
== ProcessPeb
.ImageSubsystem
;
255 #define SHELLEXECUTETEXT "ShellExecuteExW"
257 #define SHELLEXECUTETEXT "ShellExecuteExA"
260 typedef BOOL (WINAPI
*MYEX
)(LPSHELLEXECUTEINFO lpExecInfo
);
262 HANDLE
RunFile(DWORD flags
, LPTSTR filename
, LPTSTR params
,
263 LPTSTR directory
, INT show
)
265 SHELLEXECUTEINFO sei
;
270 TRACE ("RunFile(%s)\n", debugstr_aw(filename
));
271 hShell32
= LoadLibrary(_T("SHELL32.DLL"));
274 WARN ("RunFile: couldn't load SHELL32.DLL!\n");
278 hShExt
= (MYEX
)(FARPROC
)GetProcAddress(hShell32
, SHELLEXECUTETEXT
);
281 WARN ("RunFile: couldn't find ShellExecuteExA/W in SHELL32.DLL!\n");
282 FreeLibrary(hShell32
);
286 TRACE ("RunFile: ShellExecuteExA/W is at %x\n", hShExt
);
288 memset(&sei
, 0, sizeof sei
);
289 sei
.cbSize
= sizeof sei
;
291 sei
.lpFile
= filename
;
292 sei
.lpParameters
= params
;
293 sei
.lpDirectory
= directory
;
297 TRACE ("RunFile: ShellExecuteExA/W returned 0x%p\n", ret
);
299 FreeLibrary(hShell32
);
300 return ret
? sei
.hProcess
: NULL
;
306 * This command (in first) was not found in the command table
308 * Full - buffer to hold whole command line
309 * First - first word on command line
310 * Rest - rest of command line
313 Execute(LPTSTR Full
, LPTSTR First
, LPTSTR Rest
, PARSED_COMMAND
*Cmd
)
315 TCHAR szFullName
[MAX_PATH
];
316 TCHAR
*first
, *rest
, *dot
;
317 TCHAR szWindowTitle
[MAX_PATH
];
318 DWORD dwExitCode
= 0;
320 TCHAR szFullCmdLine
[CMDLINE_LENGTH
];
322 TRACE ("Execute: \'%s\' \'%s\'\n", debugstr_aw(First
), debugstr_aw(Rest
));
324 /* Though it was already parsed once, we have a different set of rules
325 for parsing before we pass to CreateProccess */
326 if (First
[0] == _T('/') || (First
[0] && First
[1] == _T(':')))
328 /* Use the entire first word as the program name (no change) */
329 FirstEnd
= First
+ _tcslen(First
);
333 /* If present in the first word, spaces and ,;=/ end the program
334 * name and become the beginning of its parameters. */
335 BOOL bInside
= FALSE
;
336 for (FirstEnd
= First
; *FirstEnd
; FirstEnd
++)
338 if (!bInside
&& (_istspace(*FirstEnd
) || _tcschr(_T(",;=/"), *FirstEnd
)))
340 bInside
^= *FirstEnd
== _T('"');
344 /* Copy the new first/rest into the buffer */
346 rest
= &Full
[FirstEnd
- First
+ 1];
347 _tcscpy(rest
, FirstEnd
);
349 *FirstEnd
= _T('\0');
350 _tcscpy(first
, First
);
352 /* check for a drive change */
353 if ((_istalpha (first
[0])) && (!_tcscmp (first
+ 1, _T(":"))))
356 if (!SetCurrentDirectory(first
))
357 /* Guess they changed disc or something, handle that gracefully and get to root */
364 working
= SetCurrentDirectory(str
);
367 if (!working
) ConErrResPuts (STRING_FREE_ERROR1
);
371 /* get the PATH environment variable and parse it */
372 /* search the PATH environment variable for the binary */
374 if (!SearchForExecutable(First
, szFullName
))
376 error_bad_command(first
);
380 GetConsoleTitle (szWindowTitle
, MAX_PATH
);
382 /* check if this is a .BAT or .CMD file */
383 dot
= _tcsrchr (szFullName
, _T('.'));
384 if (dot
&& (!_tcsicmp (dot
, _T(".bat")) || !_tcsicmp (dot
, _T(".cmd"))))
386 while (*rest
== _T(' '))
388 TRACE ("[BATCH: %s %s]\n", debugstr_aw(szFullName
), debugstr_aw(rest
));
389 dwExitCode
= Batch(szFullName
, first
, rest
, Cmd
);
393 /* exec the program */
394 PROCESS_INFORMATION prci
;
397 /* build command line for CreateProcess(): FullName + " " + rest */
398 BOOL quoted
= !!_tcschr(First
, ' ');
399 _tcscpy(szFullCmdLine
, quoted
? _T("\"") : _T(""));
400 _tcsncat(szFullCmdLine
, First
, CMDLINE_LENGTH
- _tcslen(szFullCmdLine
) - 1);
401 _tcsncat(szFullCmdLine
, quoted
? _T("\"") : _T(""), CMDLINE_LENGTH
- _tcslen(szFullCmdLine
) - 1);
405 _tcsncat(szFullCmdLine
, _T(" "), CMDLINE_LENGTH
- _tcslen(szFullCmdLine
) - 1);
406 _tcsncat(szFullCmdLine
, rest
, CMDLINE_LENGTH
- _tcslen(szFullCmdLine
) - 1);
409 TRACE ("[EXEC: %s]\n", debugstr_aw(szFullCmdLine
));
411 /* fill startup info */
412 memset (&stui
, 0, sizeof (STARTUPINFO
));
413 stui
.cb
= sizeof (STARTUPINFO
);
414 stui
.dwFlags
= STARTF_USESHOWWINDOW
;
415 stui
.wShowWindow
= SW_SHOWDEFAULT
;
417 /* Set the console to standard mode */
418 SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE
),
419 ENABLE_PROCESSED_INPUT
| ENABLE_LINE_INPUT
| ENABLE_ECHO_INPUT
);
421 if (CreateProcess(szFullName
,
426 0, /* CREATE_NEW_PROCESS_GROUP */
432 CloseHandle(prci
.hThread
);
436 // See if we can run this with ShellExecute() ie myfile.xls
437 prci
.hProcess
= RunFile(SEE_MASK_NOCLOSEPROCESS
| SEE_MASK_NO_CONSOLE
,
444 if (prci
.hProcess
!= NULL
)
446 if (IsConsoleProcess(prci
.hProcess
))
448 EnterCriticalSection(&ChildProcessRunningLock
);
449 dwChildProcessId
= prci
.dwProcessId
;
451 WaitForSingleObject(prci
.hProcess
, INFINITE
);
453 LeaveCriticalSection(&ChildProcessRunningLock
);
455 GetExitCodeProcess(prci
.hProcess
, &dwExitCode
);
456 nErrorLevel
= (INT
)dwExitCode
;
458 CloseHandle(prci
.hProcess
);
462 TRACE ("[ShellExecute failed!: %s]\n", debugstr_aw(Full
));
463 error_bad_command(first
);
467 /* Restore our default console mode */
468 SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE
),
469 ENABLE_PROCESSED_INPUT
| ENABLE_LINE_INPUT
| ENABLE_ECHO_INPUT
);
470 SetConsoleMode(GetStdHandle(STD_OUTPUT_HANDLE
),
471 ENABLE_PROCESSED_OUTPUT
| ENABLE_WRAP_AT_EOL_OUTPUT
);
474 /* Get code page if it has been changed */
475 InputCodePage
= GetConsoleCP();
476 OutputCodePage
= GetConsoleOutputCP();
477 SetConsoleTitle(szWindowTitle
);
484 * look through the internal commands and determine whether or not this
485 * command is one of them. If it is, call the command. If not, call
486 * execute to run it as an external program.
488 * first - first word on command line
489 * rest - rest of command line
492 DoCommand(LPTSTR first
, LPTSTR rest
, PARSED_COMMAND
*Cmd
)
496 LPTSTR param
; /* pointer to command's parameters */
499 BOOL nointernal
= FALSE
;
502 TRACE ("DoCommand: (\'%s\' \'%s\')\n", debugstr_aw(first
), debugstr_aw(rest
));
504 /* full command line */
505 com
= cmd_alloc((_tcslen(first
) + _tcslen(rest
) + 2) * sizeof(TCHAR
));
508 error_out_of_memory();
512 /* If present in the first word, these characters end the name of an
513 * internal command and become the beginning of its parameters. */
514 cp
= first
+ _tcscspn(first
, _T("\t +,/;=[]"));
516 for (cl
= 0; cl
< (cp
- first
); cl
++)
518 /* These characters do it too, but if one of them is present,
519 * then we check to see if the word is a file name and skip
520 * checking for internal commands if so.
521 * This allows running programs with names like "echo.exe" */
522 if (_tcschr(_T(".:\\"), first
[cl
]))
526 nointernal
= IsExistingFile(first
);
532 /* Scan internal command table */
533 for (cmdptr
= cmds
; !nointernal
&& cmdptr
->name
; cmdptr
++)
535 if (!_tcsnicmp(first
, cmdptr
->name
, cl
) && cmdptr
->name
[cl
] == _T('\0'))
541 /* Skip over whitespace to rest of line, exclude 'echo' command */
542 if (_tcsicmp(cmdptr
->name
, _T("echo")) != 0)
543 while (_istspace(*param
))
545 ret
= cmdptr
->func(param
);
551 ret
= Execute(com
, first
, rest
, Cmd
);
558 * process the command line and execute the appropriate functions
559 * full input/output redirection and piping are supported
561 INT
ParseCommandLine (LPTSTR cmd
)
564 PARSED_COMMAND
*Cmd
= ParseCommand(cmd
);
567 Ret
= ExecuteCommand(Cmd
);
573 /* Execute a command without waiting for it to finish. If it's an internal
574 * command or batch file, we must create a new cmd.exe process to handle it.
575 * TODO: For now, this just always creates a cmd.exe process.
576 * This works, but is inefficient for running external programs,
577 * which could just be run directly. */
579 ExecuteAsync(PARSED_COMMAND
*Cmd
)
581 TCHAR CmdPath
[MAX_PATH
];
582 TCHAR CmdParams
[CMDLINE_LENGTH
], *ParamsEnd
;
584 PROCESS_INFORMATION prci
;
586 /* Get the path to cmd.exe */
587 GetModuleFileName(NULL
, CmdPath
, MAX_PATH
);
589 /* Build the parameter string to pass to cmd.exe */
590 ParamsEnd
= _stpcpy(CmdParams
, _T("/S/D/C\""));
591 ParamsEnd
= Unparse(Cmd
, ParamsEnd
, &CmdParams
[CMDLINE_LENGTH
- 2]);
594 error_out_of_memory();
597 _tcscpy(ParamsEnd
, _T("\""));
599 memset(&stui
, 0, sizeof stui
);
600 stui
.cb
= sizeof(STARTUPINFO
);
601 if (!CreateProcess(CmdPath
, CmdParams
, NULL
, NULL
, TRUE
, 0,
602 NULL
, NULL
, &stui
, &prci
))
604 ErrorMessage(GetLastError(), NULL
);
608 CloseHandle(prci
.hThread
);
609 return prci
.hProcess
;
613 ExecutePipeline(PARSED_COMMAND
*Cmd
)
615 #ifdef FEATURE_REDIRECTION
616 HANDLE hInput
= NULL
;
617 HANDLE hOldConIn
= GetStdHandle(STD_INPUT_HANDLE
);
618 HANDLE hOldConOut
= GetStdHandle(STD_OUTPUT_HANDLE
);
619 HANDLE hProcess
[MAXIMUM_WAIT_OBJECTS
];
623 /* Do all but the last pipe command */
626 HANDLE hPipeRead
, hPipeWrite
;
627 if (nProcesses
> (MAXIMUM_WAIT_OBJECTS
- 2))
629 error_too_many_parameters(_T("|"));
633 /* Create the pipe that this process will write into.
634 * Make the handles non-inheritable initially, because this
635 * process shouldn't inherit the reading handle. */
636 if (!CreatePipe(&hPipeRead
, &hPipeWrite
, NULL
, 0))
642 /* The writing side of the pipe is STDOUT for this process */
643 SetHandleInformation(hPipeWrite
, HANDLE_FLAG_INHERIT
, HANDLE_FLAG_INHERIT
);
644 SetStdHandle(STD_OUTPUT_HANDLE
, hPipeWrite
);
646 /* Execute it (error check is done later for easier cleanup) */
647 hProcess
[nProcesses
] = ExecuteAsync(Cmd
->Subcommands
);
648 CloseHandle(hPipeWrite
);
652 /* The reading side of the pipe will be STDIN for the next process */
653 SetHandleInformation(hPipeRead
, HANDLE_FLAG_INHERIT
, HANDLE_FLAG_INHERIT
);
654 SetStdHandle(STD_INPUT_HANDLE
, hPipeRead
);
657 if (!hProcess
[nProcesses
])
661 Cmd
= Cmd
->Subcommands
->Next
;
662 } while (Cmd
->Type
== C_PIPE
);
664 /* The last process uses the original STDOUT */
665 SetStdHandle(STD_OUTPUT_HANDLE
, hOldConOut
);
666 hProcess
[nProcesses
] = ExecuteAsync(Cmd
);
667 if (!hProcess
[nProcesses
])
671 SetStdHandle(STD_INPUT_HANDLE
, hOldConIn
);
673 /* Wait for all processes to complete */
674 EnterCriticalSection(&ChildProcessRunningLock
);
675 WaitForMultipleObjects(nProcesses
, hProcess
, TRUE
, INFINITE
);
676 LeaveCriticalSection(&ChildProcessRunningLock
);
678 /* Use the exit code of the last process in the pipeline */
679 GetExitCodeProcess(hProcess
[nProcesses
- 1], &dwExitCode
);
680 nErrorLevel
= (INT
)dwExitCode
;
682 while (--nProcesses
>= 0)
683 CloseHandle(hProcess
[nProcesses
]);
689 while (--nProcesses
>= 0)
691 TerminateProcess(hProcess
[nProcesses
], 0);
692 CloseHandle(hProcess
[nProcesses
]);
694 SetStdHandle(STD_INPUT_HANDLE
, hOldConIn
);
695 SetStdHandle(STD_OUTPUT_HANDLE
, hOldConOut
);
700 ExecuteCommand(PARSED_COMMAND
*Cmd
)
706 if (!PerformRedirection(Cmd
->Redirections
))
713 First
= DoDelayedExpansion(Cmd
->Command
.First
);
716 Rest
= DoDelayedExpansion(Cmd
->Command
.Rest
);
719 Ret
= DoCommand(First
, Rest
, Cmd
);
728 for (Sub
= Cmd
->Subcommands
; Sub
; Sub
= Sub
->Next
)
729 Ret
= ExecuteCommand(Sub
);
732 Sub
= Cmd
->Subcommands
;
733 Ret
= ExecuteCommand(Sub
);
737 Ret
= ExecuteCommand(Sub
->Next
);
741 Sub
= Cmd
->Subcommands
;
742 Ret
= ExecuteCommand(Sub
);
744 Ret
= ExecuteCommand(Sub
->Next
);
747 ExecutePipeline(Cmd
);
750 Ret
= ExecuteIf(Cmd
);
753 Ret
= ExecuteFor(Cmd
);
757 UndoRedirection(Cmd
->Redirections
, NULL
);
762 GetEnvVar(LPCTSTR varName
)
764 static LPTSTR ret
= NULL
;
769 size
= GetEnvironmentVariable(varName
, NULL
, 0);
772 ret
= cmd_alloc(size
* sizeof(TCHAR
));
774 GetEnvironmentVariable(varName
, ret
, size
+ 1);
780 GetEnvVarOrSpecial(LPCTSTR varName
)
782 static TCHAR ret
[MAX_PATH
];
784 LPTSTR var
= GetEnvVar(varName
);
788 /* env var doesn't exist, look for a "special" one */
790 if (_tcsicmp(varName
,_T("cd")) ==0)
792 GetCurrentDirectory(MAX_PATH
, ret
);
796 else if (_tcsicmp(varName
,_T("time")) ==0)
798 return GetTimeString();
801 else if (_tcsicmp(varName
,_T("date")) ==0)
803 return GetDateString();
807 else if (_tcsicmp(varName
,_T("random")) ==0)
809 /* Get random number */
810 _itot(rand(),ret
,10);
815 else if (_tcsicmp(varName
,_T("cmdcmdline")) ==0)
817 return GetCommandLine();
820 /* %CMDEXTVERSION% */
821 else if (_tcsicmp(varName
,_T("cmdextversion")) ==0)
823 /* Set version number to 2 */
829 else if (_tcsicmp(varName
,_T("errorlevel")) ==0)
831 _itot(nErrorLevel
,ret
,10);
838 /* Handle the %~var syntax */
840 GetEnhancedVar(TCHAR
**pFormat
, LPTSTR (*GetVar
)(TCHAR
, BOOL
*))
842 static const TCHAR ModifierTable
[] = _T("dpnxfsatz");
844 M_DRIVE
= 1, /* D: drive letter */
845 M_PATH
= 2, /* P: path */
846 M_NAME
= 4, /* N: filename */
847 M_EXT
= 8, /* X: extension */
848 M_FULL
= 16, /* F: full path (drive+path+name+ext) */
849 M_SHORT
= 32, /* S: full path (drive+path+name+ext), use short names */
850 M_ATTR
= 64, /* A: attributes */
851 M_TIME
= 128, /* T: modification time */
852 M_SIZE
= 256, /* Z: file size */
855 TCHAR
*Format
, *FormatEnd
;
856 TCHAR
*PathVarName
= NULL
;
859 BOOL VariableIsParam0
;
860 TCHAR FullPath
[MAX_PATH
];
861 TCHAR FixedPath
[MAX_PATH
], *Filename
, *Extension
;
863 WIN32_FIND_DATA w32fd
;
866 static TCHAR Result
[CMDLINE_LENGTH
];
868 /* There is ambiguity between modifier characters and FOR variables;
869 * the rule that cmd uses is to pick the longest possible match.
870 * For example, if there is a %n variable, then out of %~anxnd,
871 * %~anxn will be substituted rather than just %~an. */
873 /* First, go through as many modifier characters as possible */
874 FormatEnd
= Format
= *pFormat
;
875 while (*FormatEnd
&& _tcschr(ModifierTable
, _totlower(*FormatEnd
)))
878 if (*FormatEnd
== _T('$'))
881 PathVarName
= FormatEnd
+ 1;
882 FormatEnd
= _tcschr(PathVarName
, _T(':'));
886 /* Must be immediately followed by the variable */
887 Variable
= GetVar(*++FormatEnd
, &VariableIsParam0
);
893 /* Backtrack if necessary to get a variable name match */
894 while (!(Variable
= GetVar(*FormatEnd
, &VariableIsParam0
)))
896 if (FormatEnd
== Format
)
902 for (; Format
< FormatEnd
&& *Format
!= _T('$'); Format
++)
903 Modifiers
|= 1 << (_tcschr(ModifierTable
, _totlower(*Format
)) - ModifierTable
);
905 *pFormat
= FormatEnd
+ 1;
907 /* Exclude the leading and trailing quotes */
908 VarEnd
= &Variable
[_tcslen(Variable
)];
909 if (*Variable
== _T('"'))
912 if (VarEnd
> Variable
&& VarEnd
[-1] == _T('"'))
916 if ((char *)VarEnd
- (char *)Variable
>= sizeof Result
)
918 memcpy(Result
, Variable
, (char *)VarEnd
- (char *)Variable
);
919 Result
[VarEnd
- Variable
] = _T('\0');
923 /* $PATH: syntax - search the directories listed in the
924 * specified environment variable for the file */
926 FormatEnd
[-1] = _T('\0');
927 PathVar
= GetEnvVar(PathVarName
);
928 FormatEnd
[-1] = _T(':');
930 !SearchPath(PathVar
, Result
, NULL
, MAX_PATH
, FullPath
, NULL
))
935 else if (Modifiers
== 0)
937 /* For plain %~var with no modifiers, just return the variable without quotes */
940 else if (VariableIsParam0
)
942 /* Special case: If the variable is %0 and modifier characters are present,
943 * use the batch file's path (which includes the .bat/.cmd extension)
944 * rather than the actual %0 variable (which might not). */
945 _tcscpy(FullPath
, bc
->BatchFilePath
);
949 /* Convert the variable, now without quotes, to a full path */
950 if (!GetFullPathName(Result
, MAX_PATH
, FullPath
, NULL
))
954 /* Next step is to change the path to fix letter case (e.g.
955 * C:\ReAcToS -> C:\ReactOS) and, if requested with the S modifier,
956 * replace long filenames with short. */
961 /* Copy drive letter */
965 /* Loop over each \-separated component in the path */
967 TCHAR
*Next
= _tcschr(In
, _T('\\'));
970 /* Use FindFirstFile to get the correct name */
971 if (Out
+ _tcslen(In
) + 1 >= &FixedPath
[MAX_PATH
])
974 hFind
= FindFirstFile(FixedPath
, &w32fd
);
975 /* If it doesn't exist, just leave the name as it was given */
976 if (hFind
!= INVALID_HANDLE_VALUE
)
978 LPTSTR FixedComponent
= w32fd
.cFileName
;
979 if (*w32fd
.cAlternateFileName
&&
980 ((Modifiers
& M_SHORT
) || !_tcsicmp(In
, w32fd
.cAlternateFileName
)))
982 FixedComponent
= w32fd
.cAlternateFileName
;
986 if (Out
+ _tcslen(FixedComponent
) + 1 >= &FixedPath
[MAX_PATH
])
988 _tcscpy(Out
, FixedComponent
);
995 } while (In
!= NULL
);
998 /* Build the result string. Start with attributes, modification time, and
999 * file size. If the file didn't exist, these fields will all be empty. */
1001 if (hFind
!= INVALID_HANDLE_VALUE
)
1003 if (Modifiers
& M_ATTR
)
1005 static const struct {
1008 } *Attrib
, Table
[] = {
1009 { _T('d'), FILE_ATTRIBUTE_DIRECTORY
},
1010 { _T('r'), FILE_ATTRIBUTE_READONLY
},
1011 { _T('a'), FILE_ATTRIBUTE_ARCHIVE
},
1012 { _T('h'), FILE_ATTRIBUTE_HIDDEN
},
1013 { _T('s'), FILE_ATTRIBUTE_SYSTEM
},
1014 { _T('c'), FILE_ATTRIBUTE_COMPRESSED
},
1015 { _T('o'), FILE_ATTRIBUTE_OFFLINE
},
1016 { _T('t'), FILE_ATTRIBUTE_TEMPORARY
},
1017 { _T('l'), FILE_ATTRIBUTE_REPARSE_POINT
},
1019 for (Attrib
= Table
; Attrib
!= &Table
[9]; Attrib
++)
1021 *Out
++ = w32fd
.dwFileAttributes
& Attrib
->Value
1027 if (Modifiers
& M_TIME
)
1031 FileTimeToLocalFileTime(&w32fd
.ftLastWriteTime
, &ft
);
1032 FileTimeToSystemTime(&ft
, &st
);
1034 Out
+= FormatDate(Out
, &st
, TRUE
);
1036 Out
+= FormatTime(Out
, &st
);
1039 if (Modifiers
& M_SIZE
)
1041 ULARGE_INTEGER Size
;
1042 Size
.LowPart
= w32fd
.nFileSizeLow
;
1043 Size
.HighPart
= w32fd
.nFileSizeHigh
;
1044 Out
+= _stprintf(Out
, _T("%I64u "), Size
.QuadPart
);
1048 /* When using the path-searching syntax or the S modifier,
1049 * at least part of the file path is always included.
1050 * If none of the DPNX modifiers are present, include the full path */
1051 if (PathVarName
|| (Modifiers
& M_SHORT
))
1052 if ((Modifiers
& (M_DRIVE
| M_PATH
| M_NAME
| M_EXT
)) == 0)
1053 Modifiers
|= M_FULL
;
1055 /* Now add the requested parts of the name.
1056 * With the F modifier, add all parts to form the full path. */
1057 Extension
= _tcsrchr(Filename
, _T('.'));
1058 if (Modifiers
& (M_DRIVE
| M_FULL
))
1060 *Out
++ = FixedPath
[0];
1061 *Out
++ = FixedPath
[1];
1063 if (Modifiers
& (M_PATH
| M_FULL
))
1065 memcpy(Out
, &FixedPath
[2], (char *)Filename
- (char *)&FixedPath
[2]);
1066 Out
+= Filename
- &FixedPath
[2];
1068 if (Modifiers
& (M_NAME
| M_FULL
))
1070 while (*Filename
&& Filename
!= Extension
)
1071 *Out
++ = *Filename
++;
1073 if (Modifiers
& (M_EXT
| M_FULL
))
1076 Out
= _stpcpy(Out
, Extension
);
1079 /* Trim trailing space which otherwise would appear as a
1080 * result of using the A/T/Z modifiers but no others. */
1081 while (Out
!= &Result
[0] && Out
[-1] == _T(' '))
1089 GetBatchVar(TCHAR
*varName
, UINT
*varNameLen
)
1100 varNameEnd
= varName
+ 1;
1101 ret
= GetEnhancedVar(&varNameEnd
, FindArg
);
1104 error_syntax(varName
);
1107 *varNameLen
= varNameEnd
- varName
;
1119 return FindArg(*varName
, &dummy
);
1123 // Copy over the raw params(not including the batch file name
1125 return bc
->raw_params
;
1134 SubstituteVars(TCHAR
*Src
, TCHAR
*Dest
, TCHAR Delim
)
1136 #define APPEND(From, Length) { \
1137 if (Dest + (Length) > DestEnd) \
1139 memcpy(Dest, From, (Length) * sizeof(TCHAR)); \
1141 #define APPEND1(Char) { \
1142 if (Dest >= DestEnd) \
1146 TCHAR
*DestEnd
= Dest
+ CMDLINE_LENGTH
- 1;
1160 if (bc
&& Delim
== _T('%'))
1163 Var
= GetBatchVar(Src
, &NameLen
);
1166 VarLength
= _tcslen(Var
);
1167 APPEND(Var
, VarLength
)
1173 /* Find the end of the variable name. A colon (:) will usually
1174 * end the name and begin the optional modifier, but not if it
1175 * is immediately followed by the delimiter (%VAR:%). */
1177 while (*Src
!= Delim
&& !(*Src
== _T(':') && Src
[1] != Delim
))
1186 Var
= GetEnvVarOrSpecial(SubstStart
);
1190 /* In a batch file, %NONEXISTENT% "expands" to an empty string */
1195 VarLength
= _tcslen(Var
);
1197 if (EndChr
== Delim
)
1199 /* %VAR% - use as-is */
1200 APPEND(Var
, VarLength
)
1202 else if (*Src
== _T('~'))
1204 /* %VAR:~[start][,length]% - substring
1205 * Negative values are offsets from the end */
1206 int Start
= _tcstol(Src
+ 1, &Src
, 0);
1207 int End
= VarLength
;
1210 Start
= max(Start
, 0);
1211 Start
= min(Start
, VarLength
);
1212 if (*Src
== _T(','))
1214 End
= _tcstol(Src
+ 1, &Src
, 0);
1215 End
+= (End
< 0) ? VarLength
: Start
;
1216 End
= max(End
, Start
);
1217 End
= min(End
, VarLength
);
1219 if (*Src
++ != Delim
)
1221 APPEND(&Var
[Start
], End
- Start
);
1225 /* %VAR:old=new% - replace all occurrences of old with new
1226 * %VAR:*old=new% - replace first occurrence only,
1227 * and remove everything before it */
1229 DWORD OldLength
, NewLength
;
1231 int LastMatch
= 0, i
= 0;
1233 if (*Src
== _T('*'))
1239 /* the string to replace may contain the delimiter */
1240 Src
= _tcschr(Old
= Src
, _T('='));
1243 OldLength
= Src
++ - Old
;
1247 Src
= _tcschr(New
= Src
, Delim
);
1250 NewLength
= Src
++ - New
;
1252 while (i
< VarLength
)
1254 if (_tcsnicmp(&Var
[i
], Old
, OldLength
) == 0)
1257 APPEND(&Var
[LastMatch
], i
- LastMatch
)
1258 APPEND(New
, NewLength
)
1267 APPEND(&Var
[LastMatch
], VarLength
- LastMatch
)
1279 ConOutResPrintf(STRING_ALIAS_ERROR
);
1286 /* Search the list of FOR contexts for a variable */
1287 static LPTSTR
FindForVar(TCHAR Var
, BOOL
*IsParam0
)
1291 for (Ctx
= fc
; Ctx
!= NULL
; Ctx
= Ctx
->prev
)
1293 if ((UINT
)(Var
- Ctx
->firstvar
) < Ctx
->varcount
)
1294 return Ctx
->values
[Var
- Ctx
->firstvar
];
1300 SubstituteForVars(TCHAR
*Src
, TCHAR
*Dest
)
1302 TCHAR
*DestEnd
= &Dest
[CMDLINE_LENGTH
- 1];
1305 if (Src
[0] == _T('%'))
1308 LPTSTR End
= &Src
[2];
1309 LPTSTR Value
= NULL
;
1311 if (Src
[1] == _T('~'))
1312 Value
= GetEnhancedVar(&End
, FindForVar
);
1315 Value
= FindForVar(Src
[1], &Dummy
);
1319 if (Dest
+ _tcslen(Value
) > DestEnd
)
1321 Dest
= _stpcpy(Dest
, Value
);
1326 /* Not a variable; just copy the character */
1327 if (Dest
>= DestEnd
)
1336 DoDelayedExpansion(LPTSTR Line
)
1338 TCHAR Buf1
[CMDLINE_LENGTH
];
1339 TCHAR Buf2
[CMDLINE_LENGTH
];
1341 /* First, substitute FOR variables */
1342 if (!SubstituteForVars(Line
, Buf1
))
1345 if (!bDelayedExpansion
|| !_tcschr(Buf1
, _T('!')))
1346 return cmd_dup(Buf1
);
1348 /* FIXME: Delayed substitutions actually aren't quite the same as
1349 * immediate substitutions. In particular, it's possible to escape
1350 * the exclamation point using ^. */
1351 if (!SubstituteVars(Buf1
, Buf2
, _T('!')))
1353 return cmd_dup(Buf2
);
1358 * do the prompt/input/process loop
1363 ReadLine(TCHAR
*commandline
, BOOL bMore
)
1365 TCHAR readline
[CMDLINE_LENGTH
];
1368 /* if no batch input then... */
1373 ConOutResPrintf(STRING_MORE
);
1377 /* JPP 19980807 - if echo off, don't print prompt */
1381 ConOutChar(_T('\n'));
1386 if (!ReadCommand(readline
, CMDLINE_LENGTH
- 1))
1392 if (CheckCtrlBreak(BREAK_INPUT
))
1394 ConOutChar(_T('\n'));
1401 ip
= ReadBatchLine();
1406 return SubstituteVars(ip
, commandline
, _T('%'));
1412 PARSED_COMMAND
*Cmd
;
1414 while (!bCanExit
|| !bExit
)
1416 Cmd
= ParseCommand(NULL
);
1420 ExecuteCommand(Cmd
);
1427 * control-break handler.
1429 BOOL WINAPI
BreakHandler(DWORD dwCtrlType
)
1433 static BOOL SelfGenerated
= FALSE
;
1435 if ((dwCtrlType
!= CTRL_C_EVENT
) &&
1436 (dwCtrlType
!= CTRL_BREAK_EVENT
))
1444 SelfGenerated
= FALSE
;
1449 if (!TryEnterCriticalSection(&ChildProcessRunningLock
))
1451 SelfGenerated
= TRUE
;
1452 GenerateConsoleCtrlEvent (dwCtrlType
, 0);
1457 LeaveCriticalSection(&ChildProcessRunningLock
);
1460 rec
.EventType
= KEY_EVENT
;
1461 rec
.Event
.KeyEvent
.bKeyDown
= TRUE
;
1462 rec
.Event
.KeyEvent
.wRepeatCount
= 1;
1463 rec
.Event
.KeyEvent
.wVirtualKeyCode
= _T('C');
1464 rec
.Event
.KeyEvent
.wVirtualScanCode
= _T('C') - 35;
1465 rec
.Event
.KeyEvent
.uChar
.AsciiChar
= _T('C');
1466 rec
.Event
.KeyEvent
.uChar
.UnicodeChar
= _T('C');
1467 rec
.Event
.KeyEvent
.dwControlKeyState
= RIGHT_CTRL_PRESSED
;
1469 WriteConsoleInput(hIn
,
1475 /* FIXME: Handle batch files */
1477 //ConOutPrintf(_T("^C"));
1483 VOID
AddBreakHandler (VOID
)
1485 SetConsoleCtrlHandler ((PHANDLER_ROUTINE
)BreakHandler
, TRUE
);
1489 VOID
RemoveBreakHandler (VOID
)
1491 SetConsoleCtrlHandler ((PHANDLER_ROUTINE
)BreakHandler
, FALSE
);
1496 * show commands and options that are available.
1503 /* print command list */
1504 ConOutResPuts(STRING_CMD_HELP1
);
1507 /* print feature list */
1508 ConOutResPuts(STRING_CMD_HELP2
);
1510 #ifdef FEATURE_ALIASES
1511 ConOutResPuts(STRING_CMD_HELP3
);
1513 #ifdef FEATURE_HISTORY
1514 ConOutResPuts(STRING_CMD_HELP4
);
1516 #ifdef FEATURE_UNIX_FILENAME_COMPLETION
1517 ConOutResPuts(STRING_CMD_HELP5
);
1519 #ifdef FEATURE_DIRECTORY_STACK
1520 ConOutResPuts(STRING_CMD_HELP6
);
1522 #ifdef FEATURE_REDIRECTION
1523 ConOutResPuts(STRING_CMD_HELP7
);
1525 ConOutChar(_T('\n'));
1530 ExecuteAutoRunFile(HKEY hkeyRoot
)
1532 TCHAR autorun
[2048];
1533 DWORD len
= sizeof autorun
;
1536 if (RegOpenKeyEx(hkeyRoot
,
1537 _T("SOFTWARE\\Microsoft\\Command Processor"),
1540 &hkey
) == ERROR_SUCCESS
)
1542 if (RegQueryValueEx(hkey
,
1547 &len
) == ERROR_SUCCESS
)
1550 ParseCommandLine(autorun
);
1556 /* Get the command that comes after a /C or /K switch */
1558 GetCmdLineCommand(TCHAR
*commandline
, TCHAR
*ptr
, BOOL AlwaysStrip
)
1562 while (_istspace(*ptr
))
1565 /* Remove leading quote, find final quote */
1566 if (*ptr
== _T('"') &&
1567 (LastQuote
= _tcsrchr(++ptr
, _T('"'))) != NULL
)
1570 /* Under certain circumstances, all quotes are preserved.
1571 * CMD /? documents these conditions as follows:
1573 * 2. Exactly two quotes
1574 * 3. No "special characters" between the quotes
1575 * (CMD /? says &<>()@^| but parentheses did not
1576 * trigger this rule when I tested them.)
1577 * 4. Whitespace exists between the quotes
1578 * 5. Enclosed string is an executable filename
1580 *LastQuote
= _T('\0');
1581 for (Space
= ptr
+ 1; Space
< LastQuote
; Space
++)
1583 if (_istspace(*Space
)) /* Rule 4 */
1585 if (!AlwaysStrip
&& /* Rule 1 */
1586 !_tcspbrk(ptr
, _T("\"&<>@^|")) && /* Rules 2, 3 */
1587 SearchForExecutable(ptr
, commandline
)) /* Rule 5 */
1589 /* All conditions met: preserve both the quotes */
1590 *LastQuote
= _T('"');
1591 _tcscpy(commandline
, ptr
- 1);
1598 /* The conditions were not met: remove both the
1599 * leading quote and the last quote */
1600 _tcscpy(commandline
, ptr
);
1601 _tcscpy(&commandline
[LastQuote
- ptr
], LastQuote
+ 1);
1605 /* No quotes; just copy */
1606 _tcscpy(commandline
, ptr
);
1610 * set up global initializations and process parameters
1615 HMODULE NtDllModule
;
1616 TCHAR commandline
[CMDLINE_LENGTH
];
1617 TCHAR ModuleName
[_MAX_PATH
+ 1];
1621 TCHAR
*ptr
, *cmdLine
, option
= 0;
1622 BOOL AlwaysStrip
= FALSE
;
1623 BOOL AutoRun
= TRUE
;
1625 /* get version information */
1626 osvi
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
1627 GetVersionEx (&osvi
);
1629 /* Some people like to run ReactOS cmd.exe on Win98, it helps in the
1630 * build process. So don't link implicitly against ntdll.dll, load it
1631 * dynamically instead */
1632 NtDllModule
= GetModuleHandle(TEXT("ntdll.dll"));
1633 if (NtDllModule
!= NULL
)
1635 NtQueryInformationProcessPtr
= (NtQueryInformationProcessProc
)GetProcAddress(NtDllModule
, "NtQueryInformationProcess");
1636 NtReadVirtualMemoryPtr
= (NtReadVirtualMemoryProc
)GetProcAddress(NtDllModule
, "NtReadVirtualMemory");
1641 /* get default input and output console handles */
1642 hOut
= GetStdHandle(STD_OUTPUT_HANDLE
);
1643 hIn
= GetStdHandle(STD_INPUT_HANDLE
);
1645 /* Initialize prompt support */
1648 #ifdef FEATURE_DIR_STACK
1649 /* initialize directory stack */
1650 InitDirectoryStack();
1653 #ifdef FEATURE_HISTORY
1654 /*initialize history*/
1658 /* Set COMSPEC environment variable */
1659 if (0 != GetModuleFileName (NULL
, ModuleName
, _MAX_PATH
+ 1))
1661 ModuleName
[_MAX_PATH
] = _T('\0');
1662 SetEnvironmentVariable (_T("COMSPEC"), ModuleName
);
1665 /* Add ctrl break handler */
1668 /* Set our default console mode */
1669 SetConsoleMode(hOut
, 0); // Reinitialize the console output mode
1670 SetConsoleMode(hOut
, ENABLE_PROCESSED_OUTPUT
| ENABLE_WRAP_AT_EOL_OUTPUT
);
1671 SetConsoleMode(hIn
, ENABLE_PROCESSED_INPUT
| ENABLE_LINE_INPUT
| ENABLE_ECHO_INPUT
);
1673 cmdLine
= GetCommandLine();
1674 TRACE ("[command args: %s]\n", debugstr_aw(cmdLine
));
1676 for (ptr
= cmdLine
; *ptr
; ptr
++)
1678 if (*ptr
== _T('/'))
1680 option
= _totupper(ptr
[1]);
1681 if (option
== _T('?'))
1683 ConOutResPaging(TRUE
,STRING_CMD_HELP8
);
1688 else if (option
== _T('P'))
1690 if (!IsExistingFile (_T("\\autoexec.bat")))
1692 #ifdef INCLUDE_CMD_DATE
1695 #ifdef INCLUDE_CMD_TIME
1701 ParseCommandLine (_T("\\autoexec.bat"));
1705 else if (option
== _T('A'))
1707 bUnicodeOutput
= FALSE
;
1709 else if (option
== _T('C') || option
== _T('K') || option
== _T('R'))
1711 /* Remainder of command line is a command to be run */
1714 else if (option
== _T('D'))
1718 else if (option
== _T('Q'))
1720 bDisableBatchEcho
= TRUE
;
1722 else if (option
== _T('S'))
1726 #ifdef INCLUDE_CMD_COLOR
1727 else if (!_tcsnicmp(ptr
, _T("/T:"), 3))
1729 /* process /T (color) argument */
1730 wDefColor
= (WORD
)_tcstoul(&ptr
[3], &ptr
, 16);
1731 SetScreenColor(wDefColor
, FALSE
);
1734 else if (option
== _T('U'))
1736 bUnicodeOutput
= TRUE
;
1738 else if (option
== _T('V'))
1740 bDelayedExpansion
= _tcsnicmp(&ptr
[2], _T(":OFF"), 4);
1747 /* If neither /C or /K was given, display a simple version string */
1748 ConOutChar(_T('\n'));
1749 ConOutResPrintf(STRING_REACTOS_VERSION
,
1750 _T(KERNEL_RELEASE_STR
),
1751 _T(KERNEL_VERSION_BUILD_STR
));
1752 ConOutPuts(_T("(C) Copyright 1998-") _T(COPYRIGHT_YEAR
) _T(" ReactOS Team.\n"));
1757 ExecuteAutoRunFile(HKEY_LOCAL_MACHINE
);
1758 ExecuteAutoRunFile(HKEY_CURRENT_USER
);
1763 /* Do the /C or /K command */
1764 GetCmdLineCommand(commandline
, &ptr
[2], AlwaysStrip
);
1765 nExitCode
= ParseCommandLine(commandline
);
1766 if (option
!= _T('K'))
1768 nErrorLevel
= nExitCode
;
1775 static VOID
Cleanup()
1777 /* run cmdexit.bat */
1778 if (IsExistingFile (_T("cmdexit.bat")))
1780 ConErrResPuts(STRING_CMD_ERROR5
);
1782 ParseCommandLine (_T("cmdexit.bat"));
1784 else if (IsExistingFile (_T("\\cmdexit.bat")))
1786 ConErrResPuts (STRING_CMD_ERROR5
);
1787 ParseCommandLine (_T("\\cmdexit.bat"));
1790 #ifdef FEATURE_DIECTORY_STACK
1791 /* destroy directory stack */
1792 DestroyDirectoryStack ();
1795 #ifdef FEATURE_HISTORY
1799 /* free GetEnvVar's buffer */
1802 /* Remove ctrl break handler */
1803 RemoveBreakHandler();
1805 /* Restore the default console mode */
1806 SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE
),
1807 ENABLE_PROCESSED_INPUT
| ENABLE_LINE_INPUT
| ENABLE_ECHO_INPUT
);
1808 SetConsoleMode(GetStdHandle(STD_OUTPUT_HANDLE
),
1809 ENABLE_PROCESSED_OUTPUT
| ENABLE_WRAP_AT_EOL_OUTPUT
);
1811 DeleteCriticalSection(&ChildProcessRunningLock
);
1817 int _tmain(int argc
, const TCHAR
*argv
[])
1820 TCHAR startPath
[MAX_PATH
];
1821 CONSOLE_SCREEN_BUFFER_INFO Info
;
1823 InitializeCriticalSection(&ChildProcessRunningLock
);
1824 lpOriginalEnvironment
= DuplicateEnvironment();
1826 GetCurrentDirectory(MAX_PATH
,startPath
);
1833 hConsole
= CreateFile(_T("CONOUT$"), GENERIC_READ
|GENERIC_WRITE
,
1834 FILE_SHARE_READ
|FILE_SHARE_WRITE
, NULL
,
1835 OPEN_EXISTING
, 0, NULL
);
1836 if (hConsole
!= INVALID_HANDLE_VALUE
)
1838 if (!GetConsoleScreenBufferInfo(hConsole
, &Info
))
1840 ConErrFormatMessage(GetLastError());
1841 CloseHandle(hConsole
);
1844 wDefColor
= Info
.wAttributes
;
1845 CloseHandle(hConsole
);
1848 InputCodePage
= GetConsoleCP();
1849 OutputCodePage
= GetConsoleOutputCP();
1850 CMD_ModuleHandle
= GetModuleHandle(NULL
);
1852 /* check switches on command-line */
1855 /* call prompt routine */
1858 /* do the cleanup */
1861 cmd_free(lpOriginalEnvironment
);
1863 cmd_exit(nErrorLevel
);
1864 return(nErrorLevel
);