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 CRITICAL_SECTION ChildProcessRunningLock
;
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
, UINT 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;
319 TCHAR szFullCmdLine
[CMDLINE_LENGTH
];
321 TRACE ("Execute: \'%s\' \'%s\'\n", debugstr_aw(First
), debugstr_aw(Rest
));
323 /* Though it was already parsed once, we have a different set of rules
324 for parsing before we pass to CreateProccess */
325 if (First
[0] == _T('/') || (First
[0] && First
[1] == _T(':')))
327 /* Use the entire first word as the program name (no change) */
328 FirstEnd
= First
+ _tcslen(First
);
332 /* If present in the first word, spaces and ,;=/ end the program
333 * name and become the beginning of its parameters. */
334 BOOL bInside
= FALSE
;
335 for (FirstEnd
= First
; *FirstEnd
; FirstEnd
++)
337 if (!bInside
&& (_istspace(*FirstEnd
) || _tcschr(_T(",;=/"), *FirstEnd
)))
339 bInside
^= *FirstEnd
== _T('"');
343 /* Copy the new first/rest into the buffer */
345 rest
= &Full
[FirstEnd
- First
+ 1];
346 _tcscpy(rest
, FirstEnd
);
348 *FirstEnd
= _T('\0');
349 _tcscpy(first
, First
);
351 /* check for a drive change */
352 if ((_istalpha (first
[0])) && (!_tcscmp (first
+ 1, _T(":"))))
355 if (!SetCurrentDirectory(first
))
356 /* Guess they changed disc or something, handle that gracefully and get to root */
363 working
= SetCurrentDirectory(str
);
366 if (!working
) ConErrResPuts (STRING_FREE_ERROR1
);
370 /* get the PATH environment variable and parse it */
371 /* search the PATH environment variable for the binary */
373 if (!SearchForExecutable(First
, szFullName
))
375 error_bad_command(first
);
379 GetConsoleTitle (szWindowTitle
, MAX_PATH
);
381 /* check if this is a .BAT or .CMD file */
382 dot
= _tcsrchr (szFullName
, _T('.'));
383 if (dot
&& (!_tcsicmp (dot
, _T(".bat")) || !_tcsicmp (dot
, _T(".cmd"))))
385 while (*rest
== _T(' '))
387 TRACE ("[BATCH: %s %s]\n", debugstr_aw(szFullName
), debugstr_aw(rest
));
388 dwExitCode
= Batch(szFullName
, first
, rest
, Cmd
);
392 /* exec the program */
393 PROCESS_INFORMATION prci
;
396 /* build command line for CreateProcess(): FullName + " " + rest */
397 _tcscpy(szFullCmdLine
, szFullName
);
401 _tcsncat(szFullCmdLine
, _T(" "), CMDLINE_LENGTH
- _tcslen(szFullCmdLine
));
402 _tcsncat(szFullCmdLine
, rest
, CMDLINE_LENGTH
- _tcslen(szFullCmdLine
));
405 TRACE ("[EXEC: %s]\n", debugstr_aw(szFullCmdLine
));
407 /* fill startup info */
408 memset (&stui
, 0, sizeof (STARTUPINFO
));
409 stui
.cb
= sizeof (STARTUPINFO
);
410 stui
.dwFlags
= STARTF_USESHOWWINDOW
;
411 stui
.wShowWindow
= SW_SHOWDEFAULT
;
413 // return console to standard mode
414 SetConsoleMode (GetStdHandle(STD_INPUT_HANDLE
),
415 ENABLE_LINE_INPUT
| ENABLE_PROCESSED_INPUT
| ENABLE_ECHO_INPUT
);
417 if (CreateProcess (szFullName
,
422 0, /* CREATE_NEW_PROCESS_GROUP */
429 CloseHandle(prci
.hThread
);
433 // See if we can run this with ShellExecute() ie myfile.xls
434 prci
.hProcess
= RunFile(SEE_MASK_NOCLOSEPROCESS
| SEE_MASK_NO_CONSOLE
,
441 if (prci
.hProcess
!= NULL
)
443 if (IsConsoleProcess(prci
.hProcess
))
445 EnterCriticalSection(&ChildProcessRunningLock
);
446 dwChildProcessId
= prci
.dwProcessId
;
448 WaitForSingleObject (prci
.hProcess
, INFINITE
);
450 LeaveCriticalSection(&ChildProcessRunningLock
);
452 GetExitCodeProcess (prci
.hProcess
, &dwExitCode
);
453 nErrorLevel
= (INT
)dwExitCode
;
455 CloseHandle (prci
.hProcess
);
459 TRACE ("[ShellExecute failed!: %s]\n", debugstr_aw(Full
));
460 error_bad_command (first
);
464 // restore console mode
466 GetStdHandle( STD_INPUT_HANDLE
),
467 ENABLE_PROCESSED_INPUT
);
470 /* Get code page if it has been change */
471 InputCodePage
= GetConsoleCP();
472 OutputCodePage
= GetConsoleOutputCP();
473 SetConsoleTitle (szWindowTitle
);
480 * look through the internal commands and determine whether or not this
481 * command is one of them. If it is, call the command. If not, call
482 * execute to run it as an external program.
484 * first - first word on command line
485 * rest - rest of command line
489 DoCommand(LPTSTR first
, LPTSTR rest
, PARSED_COMMAND
*Cmd
)
493 LPTSTR param
; /* pointer to command's parameters */
496 BOOL nointernal
= FALSE
;
499 TRACE ("DoCommand: (\'%s\' \'%s\')\n", debugstr_aw(first
), debugstr_aw(rest
));
501 /* full command line */
502 com
= cmd_alloc((_tcslen(first
) + _tcslen(rest
) + 2) * sizeof(TCHAR
));
505 error_out_of_memory();
509 /* If present in the first word, these characters end the name of an
510 * internal command and become the beginning of its parameters. */
511 cp
= first
+ _tcscspn(first
, _T("\t +,/;=[]"));
513 for (cl
= 0; cl
< (cp
- first
); cl
++)
515 /* These characters do it too, but if one of them is present,
516 * then we check to see if the word is a file name and skip
517 * checking for internal commands if so.
518 * This allows running programs with names like "echo.exe" */
519 if (_tcschr(_T(".:\\"), first
[cl
]))
523 nointernal
= IsExistingFile(first
);
529 /* Scan internal command table */
530 for (cmdptr
= cmds
; !nointernal
&& cmdptr
->name
; cmdptr
++)
532 if (!_tcsnicmp(first
, cmdptr
->name
, cl
) && cmdptr
->name
[cl
] == _T('\0'))
538 /* Skip over whitespace to rest of line, exclude 'echo' command */
539 if (_tcsicmp(cmdptr
->name
, _T("echo")) != 0)
540 while (_istspace(*param
))
542 ret
= cmdptr
->func(param
);
548 ret
= Execute(com
, first
, rest
, Cmd
);
555 * process the command line and execute the appropriate functions
556 * full input/output redirection and piping are supported
559 INT
ParseCommandLine (LPTSTR cmd
)
562 PARSED_COMMAND
*Cmd
= ParseCommand(cmd
);
565 Ret
= ExecuteCommand(Cmd
);
571 /* Execute a command without waiting for it to finish. If it's an internal
572 * command or batch file, we must create a new cmd.exe process to handle it.
573 * TODO: For now, this just always creates a cmd.exe process.
574 * This works, but is inefficient for running external programs,
575 * which could just be run directly. */
577 ExecuteAsync(PARSED_COMMAND
*Cmd
)
579 TCHAR CmdPath
[MAX_PATH
];
580 TCHAR CmdParams
[CMDLINE_LENGTH
], *ParamsEnd
;
582 PROCESS_INFORMATION prci
;
584 /* Get the path to cmd.exe */
585 GetModuleFileName(NULL
, CmdPath
, MAX_PATH
);
587 /* Build the parameter string to pass to cmd.exe */
588 ParamsEnd
= _stpcpy(CmdParams
, _T("/S/D/C\""));
589 ParamsEnd
= Unparse(Cmd
, ParamsEnd
, &CmdParams
[CMDLINE_LENGTH
- 2]);
592 error_out_of_memory();
595 _tcscpy(ParamsEnd
, _T("\""));
597 memset(&stui
, 0, sizeof stui
);
598 stui
.cb
= sizeof(STARTUPINFO
);
599 if (!CreateProcess(CmdPath
, CmdParams
, NULL
, NULL
, TRUE
, 0,
600 NULL
, NULL
, &stui
, &prci
))
602 ErrorMessage(GetLastError(), NULL
);
606 CloseHandle(prci
.hThread
);
607 return prci
.hProcess
;
611 ExecutePipeline(PARSED_COMMAND
*Cmd
)
613 #ifdef FEATURE_REDIRECTION
614 HANDLE hInput
= NULL
;
615 HANDLE hOldConIn
= GetStdHandle(STD_INPUT_HANDLE
);
616 HANDLE hOldConOut
= GetStdHandle(STD_OUTPUT_HANDLE
);
617 HANDLE hProcess
[MAXIMUM_WAIT_OBJECTS
];
621 /* Do all but the last pipe command */
624 HANDLE hPipeRead
, hPipeWrite
;
625 if (nProcesses
> (MAXIMUM_WAIT_OBJECTS
- 2))
627 error_too_many_parameters(_T("|"));
631 /* Create the pipe that this process will write into.
632 * Make the handles non-inheritable initially, because this
633 * process shouldn't inherit the reading handle. */
634 if (!CreatePipe(&hPipeRead
, &hPipeWrite
, NULL
, 0))
640 /* The writing side of the pipe is STDOUT for this process */
641 SetHandleInformation(hPipeWrite
, HANDLE_FLAG_INHERIT
, HANDLE_FLAG_INHERIT
);
642 SetStdHandle(STD_OUTPUT_HANDLE
, hPipeWrite
);
644 /* Execute it (error check is done later for easier cleanup) */
645 hProcess
[nProcesses
] = ExecuteAsync(Cmd
->Subcommands
);
646 CloseHandle(hPipeWrite
);
650 /* The reading side of the pipe will be STDIN for the next process */
651 SetHandleInformation(hPipeRead
, HANDLE_FLAG_INHERIT
, HANDLE_FLAG_INHERIT
);
652 SetStdHandle(STD_INPUT_HANDLE
, hPipeRead
);
655 if (!hProcess
[nProcesses
])
659 Cmd
= Cmd
->Subcommands
->Next
;
660 } while (Cmd
->Type
== C_PIPE
);
662 /* The last process uses the original STDOUT */
663 SetStdHandle(STD_OUTPUT_HANDLE
, hOldConOut
);
664 hProcess
[nProcesses
] = ExecuteAsync(Cmd
);
665 if (!hProcess
[nProcesses
])
669 SetStdHandle(STD_INPUT_HANDLE
, hOldConIn
);
671 /* Wait for all processes to complete */
672 EnterCriticalSection(&ChildProcessRunningLock
);
673 WaitForMultipleObjects(nProcesses
, hProcess
, TRUE
, INFINITE
);
674 LeaveCriticalSection(&ChildProcessRunningLock
);
676 /* Use the exit code of the last process in the pipeline */
677 GetExitCodeProcess(hProcess
[nProcesses
- 1], &dwExitCode
);
678 nErrorLevel
= (INT
)dwExitCode
;
680 while (--nProcesses
>= 0)
681 CloseHandle(hProcess
[nProcesses
]);
687 while (--nProcesses
>= 0)
689 TerminateProcess(hProcess
[nProcesses
], 0);
690 CloseHandle(hProcess
[nProcesses
]);
692 SetStdHandle(STD_INPUT_HANDLE
, hOldConIn
);
693 SetStdHandle(STD_OUTPUT_HANDLE
, hOldConOut
);
698 ExecuteCommand(PARSED_COMMAND
*Cmd
)
704 if (!PerformRedirection(Cmd
->Redirections
))
711 First
= DoDelayedExpansion(Cmd
->Command
.First
);
714 Rest
= DoDelayedExpansion(Cmd
->Command
.Rest
);
717 Ret
= DoCommand(First
, Rest
, Cmd
);
726 for (Sub
= Cmd
->Subcommands
; Sub
; Sub
= Sub
->Next
)
727 Ret
= ExecuteCommand(Sub
);
730 Sub
= Cmd
->Subcommands
;
731 Ret
= ExecuteCommand(Sub
);
735 Ret
= ExecuteCommand(Sub
->Next
);
739 Sub
= Cmd
->Subcommands
;
740 Ret
= ExecuteCommand(Sub
);
742 Ret
= ExecuteCommand(Sub
->Next
);
745 ExecutePipeline(Cmd
);
748 Ret
= ExecuteIf(Cmd
);
751 Ret
= ExecuteFor(Cmd
);
755 UndoRedirection(Cmd
->Redirections
, NULL
);
760 GetEnvVar(LPCTSTR varName
)
762 static LPTSTR ret
= NULL
;
767 size
= GetEnvironmentVariable(varName
, NULL
, 0);
770 ret
= cmd_alloc(size
* sizeof(TCHAR
));
772 GetEnvironmentVariable(varName
, ret
, size
+ 1);
778 GetEnvVarOrSpecial(LPCTSTR varName
)
780 static TCHAR ret
[MAX_PATH
];
782 LPTSTR var
= GetEnvVar(varName
);
786 /* env var doesn't exist, look for a "special" one */
788 if (_tcsicmp(varName
,_T("cd")) ==0)
790 GetCurrentDirectory(MAX_PATH
, ret
);
794 else if (_tcsicmp(varName
,_T("time")) ==0)
796 return GetTimeString();
799 else if (_tcsicmp(varName
,_T("date")) ==0)
801 return GetDateString();
805 else if (_tcsicmp(varName
,_T("random")) ==0)
807 /* Get random number */
808 _itot(rand(),ret
,10);
813 else if (_tcsicmp(varName
,_T("cmdcmdline")) ==0)
815 return GetCommandLine();
818 /* %CMDEXTVERSION% */
819 else if (_tcsicmp(varName
,_T("cmdextversion")) ==0)
821 /* Set version number to 2 */
827 else if (_tcsicmp(varName
,_T("errorlevel")) ==0)
829 _itot(nErrorLevel
,ret
,10);
836 /* Handle the %~var syntax */
838 GetEnhancedVar(TCHAR
**pFormat
, LPTSTR (*GetVar
)(TCHAR
, BOOL
*))
840 static const TCHAR ModifierTable
[] = _T("dpnxfsatz");
842 M_DRIVE
= 1, /* D: drive letter */
843 M_PATH
= 2, /* P: path */
844 M_NAME
= 4, /* N: filename */
845 M_EXT
= 8, /* X: extension */
846 M_FULL
= 16, /* F: full path (drive+path+name+ext) */
847 M_SHORT
= 32, /* S: full path (drive+path+name+ext), use short names */
848 M_ATTR
= 64, /* A: attributes */
849 M_TIME
= 128, /* T: modification time */
850 M_SIZE
= 256, /* Z: file size */
853 TCHAR
*Format
, *FormatEnd
;
854 TCHAR
*PathVarName
= NULL
;
857 BOOL VariableIsParam0
;
858 TCHAR FullPath
[MAX_PATH
];
859 TCHAR FixedPath
[MAX_PATH
], *Filename
, *Extension
;
861 WIN32_FIND_DATA w32fd
;
864 static TCHAR Result
[CMDLINE_LENGTH
];
866 /* There is ambiguity between modifier characters and FOR variables;
867 * the rule that cmd uses is to pick the longest possible match.
868 * For example, if there is a %n variable, then out of %~anxnd,
869 * %~anxn will be substituted rather than just %~an. */
871 /* First, go through as many modifier characters as possible */
872 FormatEnd
= Format
= *pFormat
;
873 while (*FormatEnd
&& _tcschr(ModifierTable
, _totlower(*FormatEnd
)))
876 if (*FormatEnd
== _T('$'))
879 PathVarName
= FormatEnd
+ 1;
880 FormatEnd
= _tcschr(PathVarName
, _T(':'));
884 /* Must be immediately followed by the variable */
885 Variable
= GetVar(*++FormatEnd
, &VariableIsParam0
);
891 /* Backtrack if necessary to get a variable name match */
892 while (!(Variable
= GetVar(*FormatEnd
, &VariableIsParam0
)))
894 if (FormatEnd
== Format
)
900 for (; Format
< FormatEnd
&& *Format
!= _T('$'); Format
++)
901 Modifiers
|= 1 << (_tcschr(ModifierTable
, _totlower(*Format
)) - ModifierTable
);
903 *pFormat
= FormatEnd
+ 1;
905 /* Exclude the leading and trailing quotes */
906 VarEnd
= &Variable
[_tcslen(Variable
)];
907 if (*Variable
== _T('"'))
910 if (VarEnd
> Variable
&& VarEnd
[-1] == _T('"'))
914 if ((char *)VarEnd
- (char *)Variable
>= sizeof Result
)
916 memcpy(Result
, Variable
, (char *)VarEnd
- (char *)Variable
);
917 Result
[VarEnd
- Variable
] = _T('\0');
921 /* $PATH: syntax - search the directories listed in the
922 * specified environment variable for the file */
924 FormatEnd
[-1] = _T('\0');
925 PathVar
= GetEnvVar(PathVarName
);
926 FormatEnd
[-1] = _T(':');
928 !SearchPath(PathVar
, Result
, NULL
, MAX_PATH
, FullPath
, NULL
))
933 else if (Modifiers
== 0)
935 /* For plain %~var with no modifiers, just return the variable without quotes */
938 else if (VariableIsParam0
)
940 /* Special case: If the variable is %0 and modifier characters are present,
941 * use the batch file's path (which includes the .bat/.cmd extension)
942 * rather than the actual %0 variable (which might not). */
943 _tcscpy(FullPath
, bc
->BatchFilePath
);
947 /* Convert the variable, now without quotes, to a full path */
948 if (!GetFullPathName(Result
, MAX_PATH
, FullPath
, NULL
))
952 /* Next step is to change the path to fix letter case (e.g.
953 * C:\ReAcToS -> C:\ReactOS) and, if requested with the S modifier,
954 * replace long filenames with short. */
959 /* Copy drive letter */
963 /* Loop over each \-separated component in the path */
965 TCHAR
*Next
= _tcschr(In
, _T('\\'));
968 /* Use FindFirstFile to get the correct name */
969 if (Out
+ _tcslen(In
) + 1 >= &FixedPath
[MAX_PATH
])
972 hFind
= FindFirstFile(FixedPath
, &w32fd
);
973 /* If it doesn't exist, just leave the name as it was given */
974 if (hFind
!= INVALID_HANDLE_VALUE
)
976 LPTSTR FixedComponent
= w32fd
.cFileName
;
977 if (*w32fd
.cAlternateFileName
&&
978 ((Modifiers
& M_SHORT
) || !_tcsicmp(In
, w32fd
.cAlternateFileName
)))
980 FixedComponent
= w32fd
.cAlternateFileName
;
984 if (Out
+ _tcslen(FixedComponent
) + 1 >= &FixedPath
[MAX_PATH
])
986 _tcscpy(Out
, FixedComponent
);
993 } while (In
!= NULL
);
996 /* Build the result string. Start with attributes, modification time, and
997 * file size. If the file didn't exist, these fields will all be empty. */
999 if (hFind
!= INVALID_HANDLE_VALUE
)
1001 if (Modifiers
& M_ATTR
)
1003 static const struct {
1006 } *Attrib
, Table
[] = {
1007 { _T('d'), FILE_ATTRIBUTE_DIRECTORY
},
1008 { _T('r'), FILE_ATTRIBUTE_READONLY
},
1009 { _T('a'), FILE_ATTRIBUTE_ARCHIVE
},
1010 { _T('h'), FILE_ATTRIBUTE_HIDDEN
},
1011 { _T('s'), FILE_ATTRIBUTE_SYSTEM
},
1012 { _T('c'), FILE_ATTRIBUTE_COMPRESSED
},
1013 { _T('o'), FILE_ATTRIBUTE_OFFLINE
},
1014 { _T('t'), FILE_ATTRIBUTE_TEMPORARY
},
1015 { _T('l'), FILE_ATTRIBUTE_REPARSE_POINT
},
1017 for (Attrib
= Table
; Attrib
!= &Table
[9]; Attrib
++)
1019 *Out
++ = w32fd
.dwFileAttributes
& Attrib
->Value
1025 if (Modifiers
& M_TIME
)
1029 FileTimeToLocalFileTime(&w32fd
.ftLastWriteTime
, &ft
);
1030 FileTimeToSystemTime(&ft
, &st
);
1032 Out
+= FormatDate(Out
, &st
, TRUE
);
1034 Out
+= FormatTime(Out
, &st
);
1037 if (Modifiers
& M_SIZE
)
1039 ULARGE_INTEGER Size
;
1040 Size
.LowPart
= w32fd
.nFileSizeLow
;
1041 Size
.HighPart
= w32fd
.nFileSizeHigh
;
1042 Out
+= _stprintf(Out
, _T("%I64u "), Size
.QuadPart
);
1046 /* When using the path-searching syntax or the S modifier,
1047 * at least part of the file path is always included.
1048 * If none of the DPNX modifiers are present, include the full path */
1049 if (PathVarName
|| (Modifiers
& M_SHORT
))
1050 if ((Modifiers
& (M_DRIVE
| M_PATH
| M_NAME
| M_EXT
)) == 0)
1051 Modifiers
|= M_FULL
;
1053 /* Now add the requested parts of the name.
1054 * With the F modifier, add all parts to form the full path. */
1055 Extension
= _tcsrchr(Filename
, _T('.'));
1056 if (Modifiers
& (M_DRIVE
| M_FULL
))
1058 *Out
++ = FixedPath
[0];
1059 *Out
++ = FixedPath
[1];
1061 if (Modifiers
& (M_PATH
| M_FULL
))
1063 memcpy(Out
, &FixedPath
[2], (char *)Filename
- (char *)&FixedPath
[2]);
1064 Out
+= Filename
- &FixedPath
[2];
1066 if (Modifiers
& (M_NAME
| M_FULL
))
1068 while (*Filename
&& Filename
!= Extension
)
1069 *Out
++ = *Filename
++;
1071 if (Modifiers
& (M_EXT
| M_FULL
))
1074 Out
= _stpcpy(Out
, Extension
);
1077 /* Trim trailing space which otherwise would appear as a
1078 * result of using the A/T/Z modifiers but no others. */
1079 while (Out
!= &Result
[0] && Out
[-1] == _T(' '))
1087 GetBatchVar(TCHAR
*varName
, UINT
*varNameLen
)
1098 varNameEnd
= varName
+ 1;
1099 ret
= GetEnhancedVar(&varNameEnd
, FindArg
);
1102 error_syntax(varName
);
1105 *varNameLen
= varNameEnd
- varName
;
1117 return FindArg(*varName
, &dummy
);
1121 // Copy over the raw params(not including the batch file name
1123 return bc
->raw_params
;
1132 SubstituteVars(TCHAR
*Src
, TCHAR
*Dest
, TCHAR Delim
)
1134 #define APPEND(From, Length) { \
1135 if (Dest + (Length) > DestEnd) \
1137 memcpy(Dest, From, (Length) * sizeof(TCHAR)); \
1139 #define APPEND1(Char) { \
1140 if (Dest >= DestEnd) \
1144 TCHAR
*DestEnd
= Dest
+ CMDLINE_LENGTH
- 1;
1158 if (bc
&& Delim
== _T('%'))
1161 Var
= GetBatchVar(Src
, &NameLen
);
1164 VarLength
= _tcslen(Var
);
1165 APPEND(Var
, VarLength
)
1171 /* Find the end of the variable name. A colon (:) will usually
1172 * end the name and begin the optional modifier, but not if it
1173 * is immediately followed by the delimiter (%VAR:%). */
1175 while (*Src
!= Delim
&& !(*Src
== _T(':') && Src
[1] != Delim
))
1184 Var
= GetEnvVarOrSpecial(SubstStart
);
1188 /* In a batch file, %NONEXISTENT% "expands" to an empty string */
1193 VarLength
= _tcslen(Var
);
1195 if (EndChr
== Delim
)
1197 /* %VAR% - use as-is */
1198 APPEND(Var
, VarLength
)
1200 else if (*Src
== _T('~'))
1202 /* %VAR:~[start][,length]% - substring
1203 * Negative values are offsets from the end */
1204 int Start
= _tcstol(Src
+ 1, &Src
, 0);
1205 int End
= VarLength
;
1208 Start
= max(Start
, 0);
1209 Start
= min(Start
, VarLength
);
1210 if (*Src
== _T(','))
1212 End
= _tcstol(Src
+ 1, &Src
, 0);
1213 End
+= (End
< 0) ? VarLength
: Start
;
1214 End
= max(End
, Start
);
1215 End
= min(End
, VarLength
);
1217 if (*Src
++ != Delim
)
1219 APPEND(&Var
[Start
], End
- Start
);
1223 /* %VAR:old=new% - replace all occurrences of old with new
1224 * %VAR:*old=new% - replace first occurrence only,
1225 * and remove everything before it */
1227 DWORD OldLength
, NewLength
;
1229 int LastMatch
= 0, i
= 0;
1231 if (*Src
== _T('*'))
1237 /* the string to replace may contain the delimiter */
1238 Src
= _tcschr(Old
= Src
, _T('='));
1241 OldLength
= Src
++ - Old
;
1245 Src
= _tcschr(New
= Src
, Delim
);
1248 NewLength
= Src
++ - New
;
1250 while (i
< VarLength
)
1252 if (_tcsnicmp(&Var
[i
], Old
, OldLength
) == 0)
1255 APPEND(&Var
[LastMatch
], i
- LastMatch
)
1256 APPEND(New
, NewLength
)
1265 APPEND(&Var
[LastMatch
], VarLength
- LastMatch
)
1277 ConOutResPrintf(STRING_ALIAS_ERROR
);
1284 /* Search the list of FOR contexts for a variable */
1285 static LPTSTR
FindForVar(TCHAR Var
, BOOL
*IsParam0
)
1289 for (Ctx
= fc
; Ctx
!= NULL
; Ctx
= Ctx
->prev
)
1290 if ((UINT
)(Var
- Ctx
->firstvar
) < Ctx
->varcount
)
1291 return Ctx
->values
[Var
- Ctx
->firstvar
];
1296 SubstituteForVars(TCHAR
*Src
, TCHAR
*Dest
)
1298 TCHAR
*DestEnd
= &Dest
[CMDLINE_LENGTH
- 1];
1301 if (Src
[0] == _T('%'))
1304 LPTSTR End
= &Src
[2];
1305 LPTSTR Value
= NULL
;
1307 if (Src
[1] == _T('~'))
1308 Value
= GetEnhancedVar(&End
, FindForVar
);
1311 Value
= FindForVar(Src
[1], &Dummy
);
1315 if (Dest
+ _tcslen(Value
) > DestEnd
)
1317 Dest
= _stpcpy(Dest
, Value
);
1322 /* Not a variable; just copy the character */
1323 if (Dest
>= DestEnd
)
1332 DoDelayedExpansion(LPTSTR Line
)
1334 TCHAR Buf1
[CMDLINE_LENGTH
];
1335 TCHAR Buf2
[CMDLINE_LENGTH
];
1337 /* First, substitute FOR variables */
1338 if (!SubstituteForVars(Line
, Buf1
))
1341 if (!bDelayedExpansion
|| !_tcschr(Buf1
, _T('!')))
1342 return cmd_dup(Buf1
);
1344 /* FIXME: Delayed substitutions actually aren't quite the same as
1345 * immediate substitutions. In particular, it's possible to escape
1346 * the exclamation point using ^. */
1347 if (!SubstituteVars(Buf1
, Buf2
, _T('!')))
1349 return cmd_dup(Buf2
);
1354 * do the prompt/input/process loop
1359 ReadLine (TCHAR
*commandline
, BOOL bMore
)
1361 TCHAR readline
[CMDLINE_LENGTH
];
1364 /* if no batch input then... */
1369 ConOutResPrintf(STRING_MORE
);
1373 /* JPP 19980807 - if echo off, don't print prompt */
1382 if (!ReadCommand(readline
, CMDLINE_LENGTH
- 1))
1388 if (CheckCtrlBreak(BREAK_INPUT
))
1390 ConOutPuts(_T("\n"));
1397 ip
= ReadBatchLine();
1402 return SubstituteVars(ip
, commandline
, _T('%'));
1408 PARSED_COMMAND
*Cmd
;
1410 while (!bCanExit
|| !bExit
)
1412 Cmd
= ParseCommand(NULL
);
1416 ExecuteCommand(Cmd
);
1423 * control-break handler.
1425 BOOL WINAPI
BreakHandler (DWORD dwCtrlType
)
1430 static BOOL SelfGenerated
= FALSE
;
1432 if ((dwCtrlType
!= CTRL_C_EVENT
) &&
1433 (dwCtrlType
!= CTRL_BREAK_EVENT
))
1441 SelfGenerated
= FALSE
;
1446 if (!TryEnterCriticalSection(&ChildProcessRunningLock
))
1448 SelfGenerated
= TRUE
;
1449 GenerateConsoleCtrlEvent (dwCtrlType
, 0);
1454 LeaveCriticalSection(&ChildProcessRunningLock
);
1457 rec
.EventType
= KEY_EVENT
;
1458 rec
.Event
.KeyEvent
.bKeyDown
= TRUE
;
1459 rec
.Event
.KeyEvent
.wRepeatCount
= 1;
1460 rec
.Event
.KeyEvent
.wVirtualKeyCode
= _T('C');
1461 rec
.Event
.KeyEvent
.wVirtualScanCode
= _T('C') - 35;
1462 rec
.Event
.KeyEvent
.uChar
.AsciiChar
= _T('C');
1463 rec
.Event
.KeyEvent
.uChar
.UnicodeChar
= _T('C');
1464 rec
.Event
.KeyEvent
.dwControlKeyState
= RIGHT_CTRL_PRESSED
;
1473 /* FIXME: Handle batch files */
1475 //ConOutPrintf(_T("^C"));
1482 VOID
AddBreakHandler (VOID
)
1484 SetConsoleCtrlHandler ((PHANDLER_ROUTINE
)BreakHandler
, TRUE
);
1488 VOID
RemoveBreakHandler (VOID
)
1490 SetConsoleCtrlHandler ((PHANDLER_ROUTINE
)BreakHandler
, FALSE
);
1495 * show commands and options that are available.
1502 /* print command list */
1503 ConOutResPuts(STRING_CMD_HELP1
);
1506 /* print feature list */
1507 ConOutResPuts(STRING_CMD_HELP2
);
1509 #ifdef FEATURE_ALIASES
1510 ConOutResPuts(STRING_CMD_HELP3
);
1512 #ifdef FEATURE_HISTORY
1513 ConOutResPuts(STRING_CMD_HELP4
);
1515 #ifdef FEATURE_UNIX_FILENAME_COMPLETION
1516 ConOutResPuts(STRING_CMD_HELP5
);
1518 #ifdef FEATURE_DIRECTORY_STACK
1519 ConOutResPuts(STRING_CMD_HELP6
);
1521 #ifdef FEATURE_REDIRECTION
1522 ConOutResPuts(STRING_CMD_HELP7
);
1524 ConOutChar(_T('\n'));
1529 ExecuteAutoRunFile(HKEY hkeyRoot
)
1531 TCHAR autorun
[2048];
1532 DWORD len
= sizeof autorun
;
1535 if (RegOpenKeyEx(hkeyRoot
,
1536 _T("SOFTWARE\\Microsoft\\Command Processor"),
1539 &hkey
) == ERROR_SUCCESS
)
1541 if(RegQueryValueEx(hkey
,
1546 &len
) == ERROR_SUCCESS
)
1549 ParseCommandLine(autorun
);
1555 /* Get the command that comes after a /C or /K switch */
1557 GetCmdLineCommand(TCHAR
*commandline
, TCHAR
*ptr
, BOOL AlwaysStrip
)
1561 while (_istspace(*ptr
))
1564 /* Remove leading quote, find final quote */
1565 if (*ptr
== _T('"') &&
1566 (LastQuote
= _tcsrchr(++ptr
, _T('"'))) != NULL
)
1569 /* Under certain circumstances, all quotes are preserved.
1570 * CMD /? documents these conditions as follows:
1572 * 2. Exactly two quotes
1573 * 3. No "special characters" between the quotes
1574 * (CMD /? says &<>()@^| but parentheses did not
1575 * trigger this rule when I tested them.)
1576 * 4. Whitespace exists between the quotes
1577 * 5. Enclosed string is an executable filename
1579 *LastQuote
= _T('\0');
1580 for (Space
= ptr
+ 1; Space
< LastQuote
; Space
++)
1582 if (_istspace(*Space
)) /* Rule 4 */
1584 if (!AlwaysStrip
&& /* Rule 1 */
1585 !_tcspbrk(ptr
, _T("\"&<>@^|")) && /* Rules 2, 3 */
1586 SearchForExecutable(ptr
, commandline
)) /* Rule 5 */
1588 /* All conditions met: preserve both the quotes */
1589 *LastQuote
= _T('"');
1590 _tcscpy(commandline
, ptr
- 1);
1597 /* The conditions were not met: remove both the
1598 * leading quote and the last quote */
1599 _tcscpy(commandline
, ptr
);
1600 _tcscpy(&commandline
[LastQuote
- ptr
], LastQuote
+ 1);
1604 /* No quotes; just copy */
1605 _tcscpy(commandline
, ptr
);
1609 * set up global initializations and process parameters
1614 HMODULE NtDllModule
;
1615 TCHAR commandline
[CMDLINE_LENGTH
];
1616 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 /* Set EnvironmentVariable PROMPT if it does not exists any env value.
1646 for you can change the EnvirommentVariable for prompt before cmd start
1647 this patch are not 100% right, if it does not exists a PROMPT value cmd should use
1648 $P$G as defualt not set EnvirommentVariable PROMPT to $P$G if it does not exists */
1649 if (GetEnvironmentVariable(_T("PROMPT"),lpBuffer
, sizeof(lpBuffer
) / sizeof(lpBuffer
[0])) == 0)
1650 SetEnvironmentVariable (_T("PROMPT"), _T("$P$G"));
1652 #ifdef FEATURE_DIR_STACK
1653 /* initialize directory stack */
1654 InitDirectoryStack ();
1657 #ifdef FEATURE_HISTORY
1658 /*initialize history*/
1662 /* Set COMSPEC environment variable */
1663 if (0 != GetModuleFileName (NULL
, ModuleName
, _MAX_PATH
+ 1))
1665 ModuleName
[_MAX_PATH
] = _T('\0');
1666 SetEnvironmentVariable (_T("COMSPEC"), ModuleName
);
1669 /* add ctrl break handler */
1673 SetConsoleMode (hIn
, ENABLE_PROCESSED_INPUT
);
1675 cmdLine
= GetCommandLine();
1676 TRACE ("[command args: %s]\n", debugstr_aw(cmdLine
));
1678 for (ptr
= cmdLine
; *ptr
; ptr
++)
1680 if (*ptr
== _T('/'))
1682 option
= _totupper(ptr
[1]);
1683 if (option
== _T('?'))
1685 ConOutResPaging(TRUE
,STRING_CMD_HELP8
);
1690 else if (option
== _T('P'))
1692 if (!IsExistingFile (_T("\\autoexec.bat")))
1694 #ifdef INCLUDE_CMD_DATE
1697 #ifdef INCLUDE_CMD_TIME
1703 ParseCommandLine (_T("\\autoexec.bat"));
1707 else if (option
== _T('A'))
1709 bUnicodeOutput
= FALSE
;
1711 else if (option
== _T('C') || option
== _T('K') || option
== _T('R'))
1713 /* Remainder of command line is a command to be run */
1716 else if (option
== _T('D'))
1720 else if (option
== _T('Q'))
1722 bDisableBatchEcho
= TRUE
;
1724 else if (option
== _T('S'))
1728 #ifdef INCLUDE_CMD_COLOR
1729 else if (!_tcsnicmp(ptr
, _T("/T:"), 3))
1731 /* process /t (color) argument */
1732 wDefColor
= (WORD
)_tcstoul(&ptr
[3], &ptr
, 16);
1733 SetScreenColor(wDefColor
, TRUE
);
1736 else if (option
== _T('U'))
1738 bUnicodeOutput
= TRUE
;
1740 else if (option
== _T('V'))
1742 bDelayedExpansion
= _tcsnicmp(&ptr
[2], _T(":OFF"), 4);
1749 /* If neither /C or /K was given, display a simple version string */
1750 ConOutResPrintf(STRING_REACTOS_VERSION
,
1751 _T(KERNEL_RELEASE_STR
),
1752 _T(KERNEL_VERSION_BUILD_STR
));
1753 ConOutPuts(_T("(C) Copyright 1998-") _T(COPYRIGHT_YEAR
) _T(" ReactOS Team."));
1758 ExecuteAutoRunFile(HKEY_LOCAL_MACHINE
);
1759 ExecuteAutoRunFile(HKEY_CURRENT_USER
);
1764 /* Do the /C or /K command */
1765 GetCmdLineCommand(commandline
, &ptr
[2], AlwaysStrip
);
1766 nExitCode
= ParseCommandLine(commandline
);
1767 if (option
!= _T('K'))
1769 nErrorLevel
= nExitCode
;
1776 static VOID
Cleanup()
1778 /* run cmdexit.bat */
1779 if (IsExistingFile (_T("cmdexit.bat")))
1781 ConErrResPuts(STRING_CMD_ERROR5
);
1783 ParseCommandLine (_T("cmdexit.bat"));
1785 else if (IsExistingFile (_T("\\cmdexit.bat")))
1787 ConErrResPuts (STRING_CMD_ERROR5
);
1788 ParseCommandLine (_T("\\cmdexit.bat"));
1791 #ifdef FEATURE_DIECTORY_STACK
1792 /* destroy directory stack */
1793 DestroyDirectoryStack ();
1796 #ifdef FEATURE_HISTORY
1800 /* free GetEnvVar's buffer */
1803 /* remove ctrl break handler */
1804 RemoveBreakHandler ();
1805 SetConsoleMode( GetStdHandle( STD_INPUT_HANDLE
),
1806 ENABLE_LINE_INPUT
| ENABLE_PROCESSED_INPUT
| ENABLE_ECHO_INPUT
);
1807 DeleteCriticalSection(&ChildProcessRunningLock
);
1813 int cmd_main (int argc
, const TCHAR
*argv
[])
1816 TCHAR startPath
[MAX_PATH
];
1817 CONSOLE_SCREEN_BUFFER_INFO Info
;
1819 InitializeCriticalSection(&ChildProcessRunningLock
);
1820 lpOriginalEnvironment
= DuplicateEnvironment();
1822 GetCurrentDirectory(MAX_PATH
,startPath
);
1829 hConsole
= CreateFile(_T("CONOUT$"), GENERIC_READ
|GENERIC_WRITE
,
1830 FILE_SHARE_READ
|FILE_SHARE_WRITE
, NULL
,
1831 OPEN_EXISTING
, 0, NULL
);
1832 if (hConsole
!= INVALID_HANDLE_VALUE
)
1834 if (!GetConsoleScreenBufferInfo(hConsole
, &Info
))
1836 ConErrFormatMessage(GetLastError());
1839 wDefColor
= Info
.wAttributes
;
1840 CloseHandle(hConsole
);
1843 InputCodePage
= GetConsoleCP();
1844 OutputCodePage
= GetConsoleOutputCP();
1845 CMD_ModuleHandle
= GetModuleHandle(NULL
);
1847 /* check switches on command-line */
1850 /* call prompt routine */
1853 /* do the cleanup */
1856 cmd_free(lpOriginalEnvironment
);
1858 cmd_exit(nErrorLevel
);
1859 return(nErrorLevel
);