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 carriage 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 memory alloc ProcessInput, the error
141 * handling for memory 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 static BOOL bWaitForCommand
= FALSE
; /* When we are executing something passed on the commandline after /c or /k */
161 INT nErrorLevel
= 0; /* Errorlevel of last launched external program */
162 CRITICAL_SECTION ChildProcessRunningLock
;
163 BOOL bUnicodeOutput
= FALSE
;
164 BOOL bDisableBatchEcho
= FALSE
;
165 BOOL bEnableExtensions
= TRUE
;
166 BOOL bDelayedExpansion
= FALSE
;
167 BOOL bTitleSet
= FALSE
;
168 DWORD dwChildProcessId
= 0;
171 LPTSTR lpOriginalEnvironment
;
172 HANDLE CMD_ModuleHandle
;
174 static NtQueryInformationProcessProc NtQueryInformationProcessPtr
= NULL
;
175 static NtReadVirtualMemoryProc NtReadVirtualMemoryPtr
= NULL
;
177 #ifdef INCLUDE_CMD_COLOR
178 WORD wDefColor
= 0; /* Default color */
184 * insert commas into a number
187 ConvertULargeInteger(ULONGLONG num
, LPTSTR des
, UINT len
, BOOL bPutSeparator
)
189 TCHAR temp
[39]; /* maximum length with nNumberGroups == 1 */
196 iTarget
= nNumberGroups
;
198 bPutSeparator
= FALSE
;
202 if (iTarget
== n
&& bPutSeparator
)
204 iTarget
+= nNumberGroups
+ 1;
205 temp
[38 - n
++] = cThousandSeparator
;
207 temp
[38 - n
++] = (TCHAR
)(num
% 10) + _T('0');
213 memcpy(des
, temp
+ 39 - n
, n
* sizeof(TCHAR
));
220 * Is a process a console process?
222 static BOOL
IsConsoleProcess(HANDLE Process
)
225 PROCESS_BASIC_INFORMATION Info
;
229 if (NULL
== NtQueryInformationProcessPtr
|| NULL
== NtReadVirtualMemoryPtr
)
234 Status
= NtQueryInformationProcessPtr (
235 Process
, ProcessBasicInformation
,
236 &Info
, sizeof(PROCESS_BASIC_INFORMATION
), NULL
);
237 if (! NT_SUCCESS(Status
))
239 WARN ("NtQueryInformationProcess failed with status %08x\n", Status
);
242 Status
= NtReadVirtualMemoryPtr (
243 Process
, Info
.PebBaseAddress
, &ProcessPeb
,
244 sizeof(PEB
), &BytesRead
);
245 if (! NT_SUCCESS(Status
) || sizeof(PEB
) != BytesRead
)
247 WARN ("Couldn't read virt mem status %08x bytes read %lu\n", Status
, BytesRead
);
251 return IMAGE_SUBSYSTEM_WINDOWS_CUI
== ProcessPeb
.ImageSubsystem
;
257 #define SHELLEXECUTETEXT "ShellExecuteExW"
259 #define SHELLEXECUTETEXT "ShellExecuteExA"
262 typedef BOOL (WINAPI
*MYEX
)(LPSHELLEXECUTEINFO lpExecInfo
);
264 HANDLE
RunFile(DWORD flags
, LPTSTR filename
, LPTSTR params
,
265 LPTSTR directory
, INT show
)
267 SHELLEXECUTEINFO sei
;
272 TRACE ("RunFile(%s)\n", debugstr_aw(filename
));
273 hShell32
= LoadLibrary(_T("SHELL32.DLL"));
276 WARN ("RunFile: couldn't load SHELL32.DLL!\n");
280 hShExt
= (MYEX
)(FARPROC
)GetProcAddress(hShell32
, SHELLEXECUTETEXT
);
283 WARN ("RunFile: couldn't find ShellExecuteExA/W in SHELL32.DLL!\n");
284 FreeLibrary(hShell32
);
288 TRACE ("RunFile: ShellExecuteExA/W is at %x\n", hShExt
);
290 memset(&sei
, 0, sizeof sei
);
291 sei
.cbSize
= sizeof sei
;
293 sei
.lpFile
= filename
;
294 sei
.lpParameters
= params
;
295 sei
.lpDirectory
= directory
;
299 TRACE ("RunFile: ShellExecuteExA/W returned 0x%p\n", ret
);
301 FreeLibrary(hShell32
);
302 return ret
? sei
.hProcess
: NULL
;
308 * This command (in first) was not found in the command table
310 * Full - buffer to hold whole command line
311 * First - first word on command line
312 * Rest - rest of command line
315 Execute(LPTSTR Full
, LPTSTR First
, LPTSTR Rest
, PARSED_COMMAND
*Cmd
)
317 TCHAR szFullName
[MAX_PATH
];
318 TCHAR
*first
, *rest
, *dot
;
319 TCHAR szWindowTitle
[MAX_PATH
], szNewTitle
[MAX_PATH
*2];
320 DWORD dwExitCode
= 0;
322 TCHAR szFullCmdLine
[CMDLINE_LENGTH
];
324 TRACE ("Execute: \'%s\' \'%s\'\n", debugstr_aw(First
), debugstr_aw(Rest
));
326 /* Though it was already parsed once, we have a different set of rules
327 for parsing before we pass to CreateProcess */
328 if (First
[0] == _T('/') || (First
[0] && First
[1] == _T(':')))
330 /* Use the entire first word as the program name (no change) */
331 FirstEnd
= First
+ _tcslen(First
);
335 /* If present in the first word, spaces and ,;=/ end the program
336 * name and become the beginning of its parameters. */
337 BOOL bInside
= FALSE
;
338 for (FirstEnd
= First
; *FirstEnd
; FirstEnd
++)
340 if (!bInside
&& (_istspace(*FirstEnd
) || _tcschr(_T(",;=/"), *FirstEnd
)))
342 bInside
^= *FirstEnd
== _T('"');
346 /* Copy the new first/rest into the buffer */
348 rest
= &Full
[FirstEnd
- First
+ 1];
349 _tcscpy(rest
, FirstEnd
);
351 *FirstEnd
= _T('\0');
352 _tcscpy(first
, First
);
354 /* check for a drive change */
355 if ((_istalpha (first
[0])) && (!_tcscmp (first
+ 1, _T(":"))))
358 if (!SetCurrentDirectory(first
))
359 /* Guess they changed disc or something, handle that gracefully and get to root */
366 working
= SetCurrentDirectory(str
);
369 if (!working
) ConErrResPuts (STRING_FREE_ERROR1
);
373 /* get the PATH environment variable and parse it */
374 /* search the PATH environment variable for the binary */
376 if (!SearchForExecutable(First
, szFullName
))
378 error_bad_command(first
);
382 GetConsoleTitle(szWindowTitle
, ARRAYSIZE(szWindowTitle
));
384 _stprintf(szNewTitle
, _T("%s - %s%s"), szWindowTitle
, First
, Rest
);
385 SetConsoleTitle(szNewTitle
);
387 /* check if this is a .BAT or .CMD file */
388 dot
= _tcsrchr (szFullName
, _T('.'));
389 if (dot
&& (!_tcsicmp (dot
, _T(".bat")) || !_tcsicmp (dot
, _T(".cmd"))))
391 while (*rest
== _T(' '))
393 TRACE ("[BATCH: %s %s]\n", debugstr_aw(szFullName
), debugstr_aw(rest
));
394 dwExitCode
= Batch(szFullName
, first
, rest
, Cmd
);
398 /* exec the program */
399 PROCESS_INFORMATION prci
;
402 /* build command line for CreateProcess(): FullName + " " + rest */
403 BOOL quoted
= !!_tcschr(First
, ' ');
404 _tcscpy(szFullCmdLine
, quoted
? _T("\"") : _T(""));
405 _tcsncat(szFullCmdLine
, First
, CMDLINE_LENGTH
- _tcslen(szFullCmdLine
) - 1);
406 _tcsncat(szFullCmdLine
, quoted
? _T("\"") : _T(""), CMDLINE_LENGTH
- _tcslen(szFullCmdLine
) - 1);
410 _tcsncat(szFullCmdLine
, _T(" "), CMDLINE_LENGTH
- _tcslen(szFullCmdLine
) - 1);
411 _tcsncat(szFullCmdLine
, rest
, CMDLINE_LENGTH
- _tcslen(szFullCmdLine
) - 1);
414 TRACE ("[EXEC: %s]\n", debugstr_aw(szFullCmdLine
));
416 /* fill startup info */
417 memset (&stui
, 0, sizeof (STARTUPINFO
));
418 stui
.cb
= sizeof (STARTUPINFO
);
419 stui
.dwFlags
= STARTF_USESHOWWINDOW
;
420 stui
.wShowWindow
= SW_SHOWDEFAULT
;
422 /* Set the console to standard mode */
423 SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE
),
424 ENABLE_PROCESSED_INPUT
| ENABLE_LINE_INPUT
| ENABLE_ECHO_INPUT
);
426 if (CreateProcess(szFullName
,
431 0, /* CREATE_NEW_PROCESS_GROUP */
437 CloseHandle(prci
.hThread
);
441 // See if we can run this with ShellExecute() ie myfile.xls
442 prci
.hProcess
= RunFile(SEE_MASK_NOCLOSEPROCESS
| SEE_MASK_NO_CONSOLE
,
449 if (prci
.hProcess
!= NULL
)
451 if (bc
!= NULL
|| bWaitForCommand
|| IsConsoleProcess(prci
.hProcess
))
453 /* when processing a batch file or starting console processes: execute synchronously */
454 EnterCriticalSection(&ChildProcessRunningLock
);
455 dwChildProcessId
= prci
.dwProcessId
;
457 WaitForSingleObject(prci
.hProcess
, INFINITE
);
459 LeaveCriticalSection(&ChildProcessRunningLock
);
461 GetExitCodeProcess(prci
.hProcess
, &dwExitCode
);
462 nErrorLevel
= (INT
)dwExitCode
;
464 CloseHandle(prci
.hProcess
);
468 TRACE ("[ShellExecute failed!: %s]\n", debugstr_aw(Full
));
469 error_bad_command(first
);
473 /* Restore our default console mode */
474 SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE
),
475 ENABLE_PROCESSED_INPUT
| ENABLE_LINE_INPUT
| ENABLE_ECHO_INPUT
);
476 SetConsoleMode(GetStdHandle(STD_OUTPUT_HANDLE
),
477 ENABLE_PROCESSED_OUTPUT
| ENABLE_WRAP_AT_EOL_OUTPUT
);
480 /* Get code page if it has been changed */
481 InputCodePage
= GetConsoleCP();
482 OutputCodePage
= GetConsoleOutputCP();
484 SetConsoleTitle(szWindowTitle
);
491 * look through the internal commands and determine whether or not this
492 * command is one of them. If it is, call the command. If not, call
493 * execute to run it as an external program.
495 * first - first word on command line
496 * rest - rest of command line
499 DoCommand(LPTSTR first
, LPTSTR rest
, PARSED_COMMAND
*Cmd
)
503 LPTSTR param
; /* pointer to command's parameters */
506 BOOL nointernal
= FALSE
;
509 TRACE ("DoCommand: (\'%s\' \'%s\')\n", debugstr_aw(first
), debugstr_aw(rest
));
511 /* full command line */
512 com
= cmd_alloc((_tcslen(first
) + _tcslen(rest
) + 2) * sizeof(TCHAR
));
515 error_out_of_memory();
519 /* If present in the first word, these characters end the name of an
520 * internal command and become the beginning of its parameters. */
521 cp
= first
+ _tcscspn(first
, _T("\t +,/;=[]"));
523 for (cl
= 0; cl
< (cp
- first
); cl
++)
525 /* These characters do it too, but if one of them is present,
526 * then we check to see if the word is a file name and skip
527 * checking for internal commands if so.
528 * This allows running programs with names like "echo.exe" */
529 if (_tcschr(_T(".:\\"), first
[cl
]))
533 nointernal
= IsExistingFile(first
);
539 /* Scan internal command table */
540 for (cmdptr
= cmds
; !nointernal
&& cmdptr
->name
; cmdptr
++)
542 if (!_tcsnicmp(first
, cmdptr
->name
, cl
) && cmdptr
->name
[cl
] == _T('\0'))
548 /* Skip over whitespace to rest of line, exclude 'echo' command */
549 if (_tcsicmp(cmdptr
->name
, _T("echo")) != 0)
550 while (_istspace(*param
))
552 ret
= cmdptr
->func(param
);
558 ret
= Execute(com
, first
, rest
, Cmd
);
565 * process the command line and execute the appropriate functions
566 * full input/output redirection and piping are supported
568 INT
ParseCommandLine (LPTSTR cmd
)
571 PARSED_COMMAND
*Cmd
= ParseCommand(cmd
);
574 Ret
= ExecuteCommand(Cmd
);
580 /* Execute a command without waiting for it to finish. If it's an internal
581 * command or batch file, we must create a new cmd.exe process to handle it.
582 * TODO: For now, this just always creates a cmd.exe process.
583 * This works, but is inefficient for running external programs,
584 * which could just be run directly. */
586 ExecuteAsync(PARSED_COMMAND
*Cmd
)
588 TCHAR CmdPath
[MAX_PATH
];
589 TCHAR CmdParams
[CMDLINE_LENGTH
], *ParamsEnd
;
591 PROCESS_INFORMATION prci
;
593 /* Get the path to cmd.exe */
594 GetModuleFileName(NULL
, CmdPath
, MAX_PATH
);
596 /* Build the parameter string to pass to cmd.exe */
597 ParamsEnd
= _stpcpy(CmdParams
, _T("/S/D/C\""));
598 ParamsEnd
= Unparse(Cmd
, ParamsEnd
, &CmdParams
[CMDLINE_LENGTH
- 2]);
601 error_out_of_memory();
604 _tcscpy(ParamsEnd
, _T("\""));
606 memset(&stui
, 0, sizeof stui
);
607 stui
.cb
= sizeof(STARTUPINFO
);
608 if (!CreateProcess(CmdPath
, CmdParams
, NULL
, NULL
, TRUE
, 0,
609 NULL
, NULL
, &stui
, &prci
))
611 ErrorMessage(GetLastError(), NULL
);
615 CloseHandle(prci
.hThread
);
616 return prci
.hProcess
;
620 ExecutePipeline(PARSED_COMMAND
*Cmd
)
622 #ifdef FEATURE_REDIRECTION
623 HANDLE hInput
= NULL
;
624 HANDLE hOldConIn
= GetStdHandle(STD_INPUT_HANDLE
);
625 HANDLE hOldConOut
= GetStdHandle(STD_OUTPUT_HANDLE
);
626 HANDLE hProcess
[MAXIMUM_WAIT_OBJECTS
];
630 /* Do all but the last pipe command */
633 HANDLE hPipeRead
, hPipeWrite
;
634 if (nProcesses
> (MAXIMUM_WAIT_OBJECTS
- 2))
636 error_too_many_parameters(_T("|"));
640 /* Create the pipe that this process will write into.
641 * Make the handles non-inheritable initially, because this
642 * process shouldn't inherit the reading handle. */
643 if (!CreatePipe(&hPipeRead
, &hPipeWrite
, NULL
, 0))
649 /* The writing side of the pipe is STDOUT for this process */
650 SetHandleInformation(hPipeWrite
, HANDLE_FLAG_INHERIT
, HANDLE_FLAG_INHERIT
);
651 SetStdHandle(STD_OUTPUT_HANDLE
, hPipeWrite
);
653 /* Execute it (error check is done later for easier cleanup) */
654 hProcess
[nProcesses
] = ExecuteAsync(Cmd
->Subcommands
);
655 CloseHandle(hPipeWrite
);
659 /* The reading side of the pipe will be STDIN for the next process */
660 SetHandleInformation(hPipeRead
, HANDLE_FLAG_INHERIT
, HANDLE_FLAG_INHERIT
);
661 SetStdHandle(STD_INPUT_HANDLE
, hPipeRead
);
664 if (!hProcess
[nProcesses
])
668 Cmd
= Cmd
->Subcommands
->Next
;
669 } while (Cmd
->Type
== C_PIPE
);
671 /* The last process uses the original STDOUT */
672 SetStdHandle(STD_OUTPUT_HANDLE
, hOldConOut
);
673 hProcess
[nProcesses
] = ExecuteAsync(Cmd
);
674 if (!hProcess
[nProcesses
])
678 SetStdHandle(STD_INPUT_HANDLE
, hOldConIn
);
680 /* Wait for all processes to complete */
681 EnterCriticalSection(&ChildProcessRunningLock
);
682 WaitForMultipleObjects(nProcesses
, hProcess
, TRUE
, INFINITE
);
683 LeaveCriticalSection(&ChildProcessRunningLock
);
685 /* Use the exit code of the last process in the pipeline */
686 GetExitCodeProcess(hProcess
[nProcesses
- 1], &dwExitCode
);
687 nErrorLevel
= (INT
)dwExitCode
;
689 while (--nProcesses
>= 0)
690 CloseHandle(hProcess
[nProcesses
]);
696 while (--nProcesses
>= 0)
698 TerminateProcess(hProcess
[nProcesses
], 0);
699 CloseHandle(hProcess
[nProcesses
]);
701 SetStdHandle(STD_INPUT_HANDLE
, hOldConIn
);
702 SetStdHandle(STD_OUTPUT_HANDLE
, hOldConOut
);
707 ExecuteCommand(PARSED_COMMAND
*Cmd
)
713 if (!PerformRedirection(Cmd
->Redirections
))
720 First
= DoDelayedExpansion(Cmd
->Command
.First
);
723 Rest
= DoDelayedExpansion(Cmd
->Command
.Rest
);
726 Ret
= DoCommand(First
, Rest
, Cmd
);
735 for (Sub
= Cmd
->Subcommands
; Sub
; Sub
= Sub
->Next
)
736 Ret
= ExecuteCommand(Sub
);
739 Sub
= Cmd
->Subcommands
;
740 Ret
= ExecuteCommand(Sub
);
744 Ret
= ExecuteCommand(Sub
->Next
);
748 Sub
= Cmd
->Subcommands
;
749 Ret
= ExecuteCommand(Sub
);
751 Ret
= ExecuteCommand(Sub
->Next
);
754 ExecutePipeline(Cmd
);
757 Ret
= ExecuteIf(Cmd
);
760 Ret
= ExecuteFor(Cmd
);
764 UndoRedirection(Cmd
->Redirections
, NULL
);
769 GetEnvVar(LPCTSTR varName
)
771 static LPTSTR ret
= NULL
;
776 size
= GetEnvironmentVariable(varName
, NULL
, 0);
779 ret
= cmd_alloc(size
* sizeof(TCHAR
));
781 GetEnvironmentVariable(varName
, ret
, size
+ 1);
787 GetEnvVarOrSpecial(LPCTSTR varName
)
789 static TCHAR ret
[MAX_PATH
];
791 LPTSTR var
= GetEnvVar(varName
);
795 /* env var doesn't exist, look for a "special" one */
797 if (_tcsicmp(varName
,_T("cd")) ==0)
799 GetCurrentDirectory(MAX_PATH
, ret
);
803 else if (_tcsicmp(varName
,_T("time")) ==0)
805 return GetTimeString();
808 else if (_tcsicmp(varName
,_T("date")) ==0)
810 return GetDateString();
814 else if (_tcsicmp(varName
,_T("random")) ==0)
816 /* Get random number */
817 _itot(rand(),ret
,10);
822 else if (_tcsicmp(varName
,_T("cmdcmdline")) ==0)
824 return GetCommandLine();
827 /* %CMDEXTVERSION% */
828 else if (_tcsicmp(varName
,_T("cmdextversion")) ==0)
830 /* Set version number to 2 */
836 else if (_tcsicmp(varName
,_T("errorlevel")) ==0)
838 _itot(nErrorLevel
,ret
,10);
845 /* Handle the %~var syntax */
847 GetEnhancedVar(TCHAR
**pFormat
, LPTSTR (*GetVar
)(TCHAR
, BOOL
*))
849 static const TCHAR ModifierTable
[] = _T("dpnxfsatz");
851 M_DRIVE
= 1, /* D: drive letter */
852 M_PATH
= 2, /* P: path */
853 M_NAME
= 4, /* N: filename */
854 M_EXT
= 8, /* X: extension */
855 M_FULL
= 16, /* F: full path (drive+path+name+ext) */
856 M_SHORT
= 32, /* S: full path (drive+path+name+ext), use short names */
857 M_ATTR
= 64, /* A: attributes */
858 M_TIME
= 128, /* T: modification time */
859 M_SIZE
= 256, /* Z: file size */
862 TCHAR
*Format
, *FormatEnd
;
863 TCHAR
*PathVarName
= NULL
;
866 BOOL VariableIsParam0
;
867 TCHAR FullPath
[MAX_PATH
];
868 TCHAR FixedPath
[MAX_PATH
], *Filename
, *Extension
;
870 WIN32_FIND_DATA w32fd
;
873 static TCHAR Result
[CMDLINE_LENGTH
];
875 /* There is ambiguity between modifier characters and FOR variables;
876 * the rule that cmd uses is to pick the longest possible match.
877 * For example, if there is a %n variable, then out of %~anxnd,
878 * %~anxn will be substituted rather than just %~an. */
880 /* First, go through as many modifier characters as possible */
881 FormatEnd
= Format
= *pFormat
;
882 while (*FormatEnd
&& _tcschr(ModifierTable
, _totlower(*FormatEnd
)))
885 if (*FormatEnd
== _T('$'))
888 PathVarName
= FormatEnd
+ 1;
889 FormatEnd
= _tcschr(PathVarName
, _T(':'));
893 /* Must be immediately followed by the variable */
894 Variable
= GetVar(*++FormatEnd
, &VariableIsParam0
);
900 /* Backtrack if necessary to get a variable name match */
901 while (!(Variable
= GetVar(*FormatEnd
, &VariableIsParam0
)))
903 if (FormatEnd
== Format
)
909 for (; Format
< FormatEnd
&& *Format
!= _T('$'); Format
++)
910 Modifiers
|= 1 << (_tcschr(ModifierTable
, _totlower(*Format
)) - ModifierTable
);
912 *pFormat
= FormatEnd
+ 1;
914 /* Exclude the leading and trailing quotes */
915 VarEnd
= &Variable
[_tcslen(Variable
)];
916 if (*Variable
== _T('"'))
919 if (VarEnd
> Variable
&& VarEnd
[-1] == _T('"'))
923 if ((char *)VarEnd
- (char *)Variable
>= sizeof Result
)
925 memcpy(Result
, Variable
, (char *)VarEnd
- (char *)Variable
);
926 Result
[VarEnd
- Variable
] = _T('\0');
930 /* $PATH: syntax - search the directories listed in the
931 * specified environment variable for the file */
933 FormatEnd
[-1] = _T('\0');
934 PathVar
= GetEnvVar(PathVarName
);
935 FormatEnd
[-1] = _T(':');
937 !SearchPath(PathVar
, Result
, NULL
, MAX_PATH
, FullPath
, NULL
))
942 else if (Modifiers
== 0)
944 /* For plain %~var with no modifiers, just return the variable without quotes */
947 else if (VariableIsParam0
)
949 /* Special case: If the variable is %0 and modifier characters are present,
950 * use the batch file's path (which includes the .bat/.cmd extension)
951 * rather than the actual %0 variable (which might not). */
952 _tcscpy(FullPath
, bc
->BatchFilePath
);
956 /* Convert the variable, now without quotes, to a full path */
957 if (!GetFullPathName(Result
, MAX_PATH
, FullPath
, NULL
))
961 /* Next step is to change the path to fix letter case (e.g.
962 * C:\ReAcToS -> C:\ReactOS) and, if requested with the S modifier,
963 * replace long filenames with short. */
968 /* Copy drive letter */
972 /* Loop over each \-separated component in the path */
974 TCHAR
*Next
= _tcschr(In
, _T('\\'));
977 /* Use FindFirstFile to get the correct name */
978 if (Out
+ _tcslen(In
) + 1 >= &FixedPath
[MAX_PATH
])
981 hFind
= FindFirstFile(FixedPath
, &w32fd
);
982 /* If it doesn't exist, just leave the name as it was given */
983 if (hFind
!= INVALID_HANDLE_VALUE
)
985 LPTSTR FixedComponent
= w32fd
.cFileName
;
986 if (*w32fd
.cAlternateFileName
&&
987 ((Modifiers
& M_SHORT
) || !_tcsicmp(In
, w32fd
.cAlternateFileName
)))
989 FixedComponent
= w32fd
.cAlternateFileName
;
993 if (Out
+ _tcslen(FixedComponent
) + 1 >= &FixedPath
[MAX_PATH
])
995 _tcscpy(Out
, FixedComponent
);
1002 } while (In
!= NULL
);
1005 /* Build the result string. Start with attributes, modification time, and
1006 * file size. If the file didn't exist, these fields will all be empty. */
1008 if (hFind
!= INVALID_HANDLE_VALUE
)
1010 if (Modifiers
& M_ATTR
)
1012 static const struct {
1015 } *Attrib
, Table
[] = {
1016 { _T('d'), FILE_ATTRIBUTE_DIRECTORY
},
1017 { _T('r'), FILE_ATTRIBUTE_READONLY
},
1018 { _T('a'), FILE_ATTRIBUTE_ARCHIVE
},
1019 { _T('h'), FILE_ATTRIBUTE_HIDDEN
},
1020 { _T('s'), FILE_ATTRIBUTE_SYSTEM
},
1021 { _T('c'), FILE_ATTRIBUTE_COMPRESSED
},
1022 { _T('o'), FILE_ATTRIBUTE_OFFLINE
},
1023 { _T('t'), FILE_ATTRIBUTE_TEMPORARY
},
1024 { _T('l'), FILE_ATTRIBUTE_REPARSE_POINT
},
1026 for (Attrib
= Table
; Attrib
!= &Table
[9]; Attrib
++)
1028 *Out
++ = w32fd
.dwFileAttributes
& Attrib
->Value
1034 if (Modifiers
& M_TIME
)
1038 FileTimeToLocalFileTime(&w32fd
.ftLastWriteTime
, &ft
);
1039 FileTimeToSystemTime(&ft
, &st
);
1041 Out
+= FormatDate(Out
, &st
, TRUE
);
1043 Out
+= FormatTime(Out
, &st
);
1046 if (Modifiers
& M_SIZE
)
1048 ULARGE_INTEGER Size
;
1049 Size
.LowPart
= w32fd
.nFileSizeLow
;
1050 Size
.HighPart
= w32fd
.nFileSizeHigh
;
1051 Out
+= _stprintf(Out
, _T("%I64u "), Size
.QuadPart
);
1055 /* When using the path-searching syntax or the S modifier,
1056 * at least part of the file path is always included.
1057 * If none of the DPNX modifiers are present, include the full path */
1058 if (PathVarName
|| (Modifiers
& M_SHORT
))
1059 if ((Modifiers
& (M_DRIVE
| M_PATH
| M_NAME
| M_EXT
)) == 0)
1060 Modifiers
|= M_FULL
;
1062 /* Now add the requested parts of the name.
1063 * With the F modifier, add all parts to form the full path. */
1064 Extension
= _tcsrchr(Filename
, _T('.'));
1065 if (Modifiers
& (M_DRIVE
| M_FULL
))
1067 *Out
++ = FixedPath
[0];
1068 *Out
++ = FixedPath
[1];
1070 if (Modifiers
& (M_PATH
| M_FULL
))
1072 memcpy(Out
, &FixedPath
[2], (char *)Filename
- (char *)&FixedPath
[2]);
1073 Out
+= Filename
- &FixedPath
[2];
1075 if (Modifiers
& (M_NAME
| M_FULL
))
1077 while (*Filename
&& Filename
!= Extension
)
1078 *Out
++ = *Filename
++;
1080 if (Modifiers
& (M_EXT
| M_FULL
))
1083 Out
= _stpcpy(Out
, Extension
);
1086 /* Trim trailing space which otherwise would appear as a
1087 * result of using the A/T/Z modifiers but no others. */
1088 while (Out
!= &Result
[0] && Out
[-1] == _T(' '))
1096 GetBatchVar(TCHAR
*varName
, UINT
*varNameLen
)
1107 varNameEnd
= varName
+ 1;
1108 ret
= GetEnhancedVar(&varNameEnd
, FindArg
);
1111 error_syntax(varName
);
1114 *varNameLen
= varNameEnd
- varName
;
1126 return FindArg(*varName
, &dummy
);
1130 // Copy over the raw params(not including the batch file name
1132 return bc
->raw_params
;
1141 SubstituteVars(TCHAR
*Src
, TCHAR
*Dest
, TCHAR Delim
)
1143 #define APPEND(From, Length) { \
1144 if (Dest + (Length) > DestEnd) \
1146 memcpy(Dest, From, (Length) * sizeof(TCHAR)); \
1148 #define APPEND1(Char) { \
1149 if (Dest >= DestEnd) \
1153 TCHAR
*DestEnd
= Dest
+ CMDLINE_LENGTH
- 1;
1167 if (bc
&& Delim
== _T('%'))
1170 Var
= GetBatchVar(Src
, &NameLen
);
1173 VarLength
= _tcslen(Var
);
1174 APPEND(Var
, VarLength
)
1180 /* Find the end of the variable name. A colon (:) will usually
1181 * end the name and begin the optional modifier, but not if it
1182 * is immediately followed by the delimiter (%VAR:%). */
1184 while (*Src
!= Delim
&& !(*Src
== _T(':') && Src
[1] != Delim
))
1193 Var
= GetEnvVarOrSpecial(SubstStart
);
1197 /* In a batch file, %NONEXISTENT% "expands" to an empty string */
1202 VarLength
= _tcslen(Var
);
1204 if (EndChr
== Delim
)
1206 /* %VAR% - use as-is */
1207 APPEND(Var
, VarLength
)
1209 else if (*Src
== _T('~'))
1211 /* %VAR:~[start][,length]% - substring
1212 * Negative values are offsets from the end */
1213 int Start
= _tcstol(Src
+ 1, &Src
, 0);
1214 int End
= VarLength
;
1217 Start
= max(Start
, 0);
1218 Start
= min(Start
, VarLength
);
1219 if (*Src
== _T(','))
1221 End
= _tcstol(Src
+ 1, &Src
, 0);
1222 End
+= (End
< 0) ? VarLength
: Start
;
1223 End
= max(End
, Start
);
1224 End
= min(End
, VarLength
);
1226 if (*Src
++ != Delim
)
1228 APPEND(&Var
[Start
], End
- Start
);
1232 /* %VAR:old=new% - replace all occurrences of old with new
1233 * %VAR:*old=new% - replace first occurrence only,
1234 * and remove everything before it */
1236 DWORD OldLength
, NewLength
;
1238 int LastMatch
= 0, i
= 0;
1240 if (*Src
== _T('*'))
1246 /* the string to replace may contain the delimiter */
1247 Src
= _tcschr(Old
= Src
, _T('='));
1250 OldLength
= Src
++ - Old
;
1254 Src
= _tcschr(New
= Src
, Delim
);
1257 NewLength
= Src
++ - New
;
1259 while (i
< VarLength
)
1261 if (_tcsnicmp(&Var
[i
], Old
, OldLength
) == 0)
1264 APPEND(&Var
[LastMatch
], i
- LastMatch
)
1265 APPEND(New
, NewLength
)
1274 APPEND(&Var
[LastMatch
], VarLength
- LastMatch
)
1286 ConOutResPrintf(STRING_ALIAS_ERROR
);
1293 /* Search the list of FOR contexts for a variable */
1294 static LPTSTR
FindForVar(TCHAR Var
, BOOL
*IsParam0
)
1298 for (Ctx
= fc
; Ctx
!= NULL
; Ctx
= Ctx
->prev
)
1300 if ((UINT
)(Var
- Ctx
->firstvar
) < Ctx
->varcount
)
1301 return Ctx
->values
[Var
- Ctx
->firstvar
];
1307 SubstituteForVars(TCHAR
*Src
, TCHAR
*Dest
)
1309 TCHAR
*DestEnd
= &Dest
[CMDLINE_LENGTH
- 1];
1312 if (Src
[0] == _T('%'))
1315 LPTSTR End
= &Src
[2];
1316 LPTSTR Value
= NULL
;
1318 if (Src
[1] == _T('~'))
1319 Value
= GetEnhancedVar(&End
, FindForVar
);
1322 Value
= FindForVar(Src
[1], &Dummy
);
1326 if (Dest
+ _tcslen(Value
) > DestEnd
)
1328 Dest
= _stpcpy(Dest
, Value
);
1333 /* Not a variable; just copy the character */
1334 if (Dest
>= DestEnd
)
1343 DoDelayedExpansion(LPTSTR Line
)
1345 TCHAR Buf1
[CMDLINE_LENGTH
];
1346 TCHAR Buf2
[CMDLINE_LENGTH
];
1348 /* First, substitute FOR variables */
1349 if (!SubstituteForVars(Line
, Buf1
))
1352 if (!bDelayedExpansion
|| !_tcschr(Buf1
, _T('!')))
1353 return cmd_dup(Buf1
);
1355 /* FIXME: Delayed substitutions actually aren't quite the same as
1356 * immediate substitutions. In particular, it's possible to escape
1357 * the exclamation point using ^. */
1358 if (!SubstituteVars(Buf1
, Buf2
, _T('!')))
1360 return cmd_dup(Buf2
);
1365 * do the prompt/input/process loop
1370 ReadLine(TCHAR
*commandline
, BOOL bMore
)
1372 TCHAR readline
[CMDLINE_LENGTH
];
1375 /* if no batch input then... */
1380 ConOutResPrintf(STRING_MORE
);
1384 /* JPP 19980807 - if echo off, don't print prompt */
1388 ConOutChar(_T('\n'));
1393 if (!ReadCommand(readline
, CMDLINE_LENGTH
- 1))
1399 if (CheckCtrlBreak(BREAK_INPUT
))
1401 ConOutChar(_T('\n'));
1408 ip
= ReadBatchLine();
1413 return SubstituteVars(ip
, commandline
, _T('%'));
1419 PARSED_COMMAND
*Cmd
;
1421 while (!bCanExit
|| !bExit
)
1423 Cmd
= ParseCommand(NULL
);
1427 ExecuteCommand(Cmd
);
1434 * control-break handler.
1436 BOOL WINAPI
BreakHandler(DWORD dwCtrlType
)
1440 static BOOL SelfGenerated
= FALSE
;
1442 if ((dwCtrlType
!= CTRL_C_EVENT
) &&
1443 (dwCtrlType
!= CTRL_BREAK_EVENT
))
1451 SelfGenerated
= FALSE
;
1456 if (!TryEnterCriticalSection(&ChildProcessRunningLock
))
1458 SelfGenerated
= TRUE
;
1459 GenerateConsoleCtrlEvent (dwCtrlType
, 0);
1464 LeaveCriticalSection(&ChildProcessRunningLock
);
1467 rec
.EventType
= KEY_EVENT
;
1468 rec
.Event
.KeyEvent
.bKeyDown
= TRUE
;
1469 rec
.Event
.KeyEvent
.wRepeatCount
= 1;
1470 rec
.Event
.KeyEvent
.wVirtualKeyCode
= _T('C');
1471 rec
.Event
.KeyEvent
.wVirtualScanCode
= _T('C') - 35;
1472 rec
.Event
.KeyEvent
.uChar
.AsciiChar
= _T('C');
1473 rec
.Event
.KeyEvent
.uChar
.UnicodeChar
= _T('C');
1474 rec
.Event
.KeyEvent
.dwControlKeyState
= RIGHT_CTRL_PRESSED
;
1476 WriteConsoleInput(hIn
,
1482 /* FIXME: Handle batch files */
1484 //ConOutPrintf(_T("^C"));
1490 VOID
AddBreakHandler (VOID
)
1492 SetConsoleCtrlHandler ((PHANDLER_ROUTINE
)BreakHandler
, TRUE
);
1496 VOID
RemoveBreakHandler (VOID
)
1498 SetConsoleCtrlHandler ((PHANDLER_ROUTINE
)BreakHandler
, FALSE
);
1503 * show commands and options that are available.
1510 /* print command list */
1511 ConOutResPuts(STRING_CMD_HELP1
);
1514 /* print feature list */
1515 ConOutResPuts(STRING_CMD_HELP2
);
1517 #ifdef FEATURE_ALIASES
1518 ConOutResPuts(STRING_CMD_HELP3
);
1520 #ifdef FEATURE_HISTORY
1521 ConOutResPuts(STRING_CMD_HELP4
);
1523 #ifdef FEATURE_UNIX_FILENAME_COMPLETION
1524 ConOutResPuts(STRING_CMD_HELP5
);
1526 #ifdef FEATURE_DIRECTORY_STACK
1527 ConOutResPuts(STRING_CMD_HELP6
);
1529 #ifdef FEATURE_REDIRECTION
1530 ConOutResPuts(STRING_CMD_HELP7
);
1532 ConOutChar(_T('\n'));
1538 LoadRegistrySettings(HKEY hKeyRoot
)
1543 * Buffer big enough to hold the string L"4294967295",
1544 * corresponding to the literal 0xFFFFFFFF (MAX_ULONG) in decimal.
1549 lRet
= RegOpenKeyEx(hKeyRoot
,
1550 _T("Software\\Microsoft\\Command Processor"),
1554 if (lRet
!= ERROR_SUCCESS
)
1557 #ifdef INCLUDE_CMD_COLOR
1558 len
= sizeof(Buffer
);
1559 lRet
= RegQueryValueEx(hKey
,
1565 if (lRet
== ERROR_SUCCESS
)
1567 /* Overwrite the default attributes */
1568 if (dwType
== REG_DWORD
)
1569 wDefColor
= (WORD
)*(PDWORD
)Buffer
;
1570 else if (dwType
== REG_SZ
)
1571 wDefColor
= (WORD
)_tcstol((PTSTR
)Buffer
, NULL
, 0);
1573 // else, use the default attributes retrieved before.
1577 len
= sizeof(Buffer
);
1578 lRet
= RegQueryValueEx(hKey
,
1579 _T("DisableUNCCheck"),
1584 if (lRet
== ERROR_SUCCESS
)
1586 /* Overwrite the default setting */
1587 if (dwType
== REG_DWORD
)
1588 bDisableUNCCheck
= !!*(PDWORD
)Buffer
;
1589 else if (dwType
== REG_SZ
)
1590 bDisableUNCCheck
= (_ttol((PTSTR
)Buffer
) == 1);
1592 // else, use the default setting set globally.
1595 len
= sizeof(Buffer
);
1596 lRet
= RegQueryValueEx(hKey
,
1597 _T("DelayedExpansion"),
1602 if (lRet
== ERROR_SUCCESS
)
1604 /* Overwrite the default setting */
1605 if (dwType
== REG_DWORD
)
1606 bDelayedExpansion
= !!*(PDWORD
)Buffer
;
1607 else if (dwType
== REG_SZ
)
1608 bDelayedExpansion
= (_ttol((PTSTR
)Buffer
) == 1);
1610 // else, use the default setting set globally.
1612 len
= sizeof(Buffer
);
1613 lRet
= RegQueryValueEx(hKey
,
1614 _T("EnableExtensions"),
1619 if (lRet
== ERROR_SUCCESS
)
1621 /* Overwrite the default setting */
1622 if (dwType
== REG_DWORD
)
1623 bEnableExtensions
= !!*(PDWORD
)Buffer
;
1624 else if (dwType
== REG_SZ
)
1625 bEnableExtensions
= (_ttol((PTSTR
)Buffer
) == 1);
1627 // else, use the default setting set globally.
1629 len
= sizeof(Buffer
);
1630 lRet
= RegQueryValueEx(hKey
,
1631 _T("CompletionChar"),
1636 if (lRet
== ERROR_SUCCESS
)
1638 /* Overwrite the default setting */
1639 if (dwType
== REG_DWORD
)
1640 AutoCompletionChar
= (TCHAR
)*(PDWORD
)Buffer
;
1641 else if (dwType
== REG_SZ
)
1642 AutoCompletionChar
= (TCHAR
)_tcstol((PTSTR
)Buffer
, NULL
, 0);
1644 // else, use the default setting set globally.
1646 /* Validity check */
1647 if (IS_COMPLETION_DISABLED(AutoCompletionChar
))
1649 /* Disable autocompletion */
1650 AutoCompletionChar
= 0x20;
1653 len
= sizeof(Buffer
);
1654 lRet
= RegQueryValueEx(hKey
,
1655 _T("PathCompletionChar"),
1660 if (lRet
== ERROR_SUCCESS
)
1662 /* Overwrite the default setting */
1663 if (dwType
== REG_DWORD
)
1664 PathCompletionChar
= (TCHAR
)*(PDWORD
)Buffer
;
1665 else if (dwType
== REG_SZ
)
1666 PathCompletionChar
= (TCHAR
)_tcstol((PTSTR
)Buffer
, NULL
, 0);
1668 // else, use the default setting set globally.
1670 /* Validity check */
1671 if (IS_COMPLETION_DISABLED(PathCompletionChar
))
1673 /* Disable autocompletion */
1674 PathCompletionChar
= 0x20;
1677 /* Adjust completion chars */
1678 if (PathCompletionChar
>= 0x20 && AutoCompletionChar
< 0x20)
1679 PathCompletionChar
= AutoCompletionChar
;
1680 else if (AutoCompletionChar
>= 0x20 && PathCompletionChar
< 0x20)
1681 AutoCompletionChar
= PathCompletionChar
;
1687 ExecuteAutoRunFile(HKEY hKeyRoot
)
1689 TCHAR autorun
[2048];
1690 DWORD len
= sizeof autorun
;
1693 if (RegOpenKeyEx(hKeyRoot
,
1694 _T("SOFTWARE\\Microsoft\\Command Processor"),
1697 &hkey
) == ERROR_SUCCESS
)
1699 if (RegQueryValueEx(hkey
,
1704 &len
) == ERROR_SUCCESS
)
1707 ParseCommandLine(autorun
);
1713 /* Get the command that comes after a /C or /K switch */
1715 GetCmdLineCommand(TCHAR
*commandline
, TCHAR
*ptr
, BOOL AlwaysStrip
)
1719 while (_istspace(*ptr
))
1722 /* Remove leading quote, find final quote */
1723 if (*ptr
== _T('"') &&
1724 (LastQuote
= _tcsrchr(++ptr
, _T('"'))) != NULL
)
1727 /* Under certain circumstances, all quotes are preserved.
1728 * CMD /? documents these conditions as follows:
1730 * 2. Exactly two quotes
1731 * 3. No "special characters" between the quotes
1732 * (CMD /? says &<>()@^| but parentheses did not
1733 * trigger this rule when I tested them.)
1734 * 4. Whitespace exists between the quotes
1735 * 5. Enclosed string is an executable filename
1737 *LastQuote
= _T('\0');
1738 for (Space
= ptr
+ 1; Space
< LastQuote
; Space
++)
1740 if (_istspace(*Space
)) /* Rule 4 */
1742 if (!AlwaysStrip
&& /* Rule 1 */
1743 !_tcspbrk(ptr
, _T("\"&<>@^|")) && /* Rules 2, 3 */
1744 SearchForExecutable(ptr
, commandline
)) /* Rule 5 */
1746 /* All conditions met: preserve both the quotes */
1747 *LastQuote
= _T('"');
1748 _tcscpy(commandline
, ptr
- 1);
1755 /* The conditions were not met: remove both the
1756 * leading quote and the last quote */
1757 _tcscpy(commandline
, ptr
);
1758 _tcscpy(&commandline
[LastQuote
- ptr
], LastQuote
+ 1);
1762 /* No quotes; just copy */
1763 _tcscpy(commandline
, ptr
);
1767 #ifdef INCLUDE_CMD_COLOR
1769 BOOL
ConGetDefaultAttributes(PWORD pwDefAttr
)
1773 CONSOLE_SCREEN_BUFFER_INFO csbi
;
1775 /* Do not modify *pwDefAttr if we fail, in which case use default attributes */
1777 hConsole
= CreateFile(_T("CONOUT$"), GENERIC_READ
|GENERIC_WRITE
,
1778 FILE_SHARE_READ
|FILE_SHARE_WRITE
, NULL
,
1779 OPEN_EXISTING
, 0, NULL
);
1780 if (hConsole
== INVALID_HANDLE_VALUE
)
1781 return FALSE
; // No default console
1783 Success
= GetConsoleScreenBufferInfo(hConsole
, &csbi
);
1785 *pwDefAttr
= csbi
.wAttributes
;
1787 CloseHandle(hConsole
);
1795 * Set up global initializations and process parameters
1800 HMODULE NtDllModule
;
1801 TCHAR commandline
[CMDLINE_LENGTH
];
1802 TCHAR ModuleName
[_MAX_PATH
+ 1];
1805 TCHAR
*ptr
, *cmdLine
, option
= 0;
1806 BOOL AlwaysStrip
= FALSE
;
1807 BOOL AutoRun
= TRUE
;
1809 /* Get version information */
1812 /* Some people like to run ReactOS cmd.exe on Win98, it helps in the
1813 * build process. So don't link implicitly against ntdll.dll, load it
1814 * dynamically instead */
1815 NtDllModule
= GetModuleHandle(TEXT("ntdll.dll"));
1816 if (NtDllModule
!= NULL
)
1818 NtQueryInformationProcessPtr
= (NtQueryInformationProcessProc
)GetProcAddress(NtDllModule
, "NtQueryInformationProcess");
1819 NtReadVirtualMemoryPtr
= (NtReadVirtualMemoryProc
)GetProcAddress(NtDllModule
, "NtReadVirtualMemory");
1822 /* Load the registry settings */
1823 LoadRegistrySettings(HKEY_LOCAL_MACHINE
);
1824 LoadRegistrySettings(HKEY_CURRENT_USER
);
1826 /* Initialize our locale */
1829 /* Get default input and output console handles */
1830 hOut
= GetStdHandle(STD_OUTPUT_HANDLE
);
1831 hIn
= GetStdHandle(STD_INPUT_HANDLE
);
1833 /* Initialize prompt support */
1836 #ifdef FEATURE_DIR_STACK
1837 /* Initialize directory stack */
1838 InitDirectoryStack();
1841 #ifdef FEATURE_HISTORY
1842 /* Initialize history */
1846 /* Set COMSPEC environment variable */
1847 if (GetModuleFileName(NULL
, ModuleName
, ARRAYSIZE(ModuleName
)) != 0)
1849 ModuleName
[_MAX_PATH
] = _T('\0');
1850 SetEnvironmentVariable (_T("COMSPEC"), ModuleName
);
1853 /* Add ctrl break handler */
1856 /* Set our default console mode */
1857 SetConsoleMode(hOut
, 0); // Reinitialize the console output mode
1858 SetConsoleMode(hOut
, ENABLE_PROCESSED_OUTPUT
| ENABLE_WRAP_AT_EOL_OUTPUT
);
1859 SetConsoleMode(hIn
, ENABLE_PROCESSED_INPUT
| ENABLE_LINE_INPUT
| ENABLE_ECHO_INPUT
);
1861 cmdLine
= GetCommandLine();
1862 TRACE ("[command args: %s]\n", debugstr_aw(cmdLine
));
1864 for (ptr
= cmdLine
; *ptr
; ptr
++)
1866 if (*ptr
== _T('/'))
1868 option
= _totupper(ptr
[1]);
1869 if (option
== _T('?'))
1871 ConOutResPaging(TRUE
,STRING_CMD_HELP8
);
1876 else if (option
== _T('P'))
1878 if (!IsExistingFile (_T("\\autoexec.bat")))
1880 #ifdef INCLUDE_CMD_DATE
1883 #ifdef INCLUDE_CMD_TIME
1889 ParseCommandLine (_T("\\autoexec.bat"));
1893 else if (option
== _T('A'))
1895 bUnicodeOutput
= FALSE
;
1897 else if (option
== _T('C') || option
== _T('K') || option
== _T('R'))
1899 /* Remainder of command line is a command to be run */
1902 else if (option
== _T('D'))
1906 else if (option
== _T('Q'))
1908 bDisableBatchEcho
= TRUE
;
1910 else if (option
== _T('S'))
1914 #ifdef INCLUDE_CMD_COLOR
1915 else if (!_tcsnicmp(ptr
, _T("/T:"), 3))
1917 /* Process /T (color) argument; overwrite any previous settings */
1918 wDefColor
= (WORD
)_tcstoul(&ptr
[3], &ptr
, 16);
1921 else if (option
== _T('U'))
1923 bUnicodeOutput
= TRUE
;
1925 else if (option
== _T('V'))
1927 // FIXME: Check validity of the parameter given to V !
1928 bDelayedExpansion
= _tcsnicmp(&ptr
[2], _T(":OFF"), 4);
1930 else if (option
== _T('E'))
1932 // FIXME: Check validity of the parameter given to E !
1933 bEnableExtensions
= _tcsnicmp(&ptr
[2], _T(":OFF"), 4);
1935 else if (option
== _T('X'))
1937 /* '/X' is identical to '/E:ON' */
1938 bEnableExtensions
= TRUE
;
1940 else if (option
== _T('Y'))
1942 /* '/Y' is identical to '/E:OFF' */
1943 bEnableExtensions
= FALSE
;
1948 #ifdef INCLUDE_CMD_COLOR
1952 * If we still do not have the console colour attribute set,
1953 * retrieve the default one.
1955 ConGetDefaultAttributes(&wDefColor
);
1959 SetScreenColor(wDefColor
, FALSE
);
1964 /* If neither /C or /K was given, display a simple version string */
1965 ConOutChar(_T('\n'));
1966 ConOutResPrintf(STRING_REACTOS_VERSION
,
1967 _T(KERNEL_VERSION_STR
),
1968 _T(KERNEL_VERSION_BUILD_STR
));
1969 ConOutPuts(_T("(C) Copyright 1998-") _T(COPYRIGHT_YEAR
) _T(" ReactOS Team.\n"));
1974 ExecuteAutoRunFile(HKEY_LOCAL_MACHINE
);
1975 ExecuteAutoRunFile(HKEY_CURRENT_USER
);
1980 /* Do the /C or /K command */
1981 GetCmdLineCommand(commandline
, &ptr
[2], AlwaysStrip
);
1982 bWaitForCommand
= TRUE
;
1983 nExitCode
= ParseCommandLine(commandline
);
1984 bWaitForCommand
= FALSE
;
1985 if (option
!= _T('K'))
1987 nErrorLevel
= nExitCode
;
1994 static VOID
Cleanup(VOID
)
1996 /* run cmdexit.bat */
1997 if (IsExistingFile (_T("cmdexit.bat")))
1999 ConErrResPuts(STRING_CMD_ERROR5
);
2001 ParseCommandLine (_T("cmdexit.bat"));
2003 else if (IsExistingFile (_T("\\cmdexit.bat")))
2005 ConErrResPuts (STRING_CMD_ERROR5
);
2006 ParseCommandLine (_T("\\cmdexit.bat"));
2009 #ifdef FEATURE_DIRECTORY_STACK
2010 /* destroy directory stack */
2011 DestroyDirectoryStack ();
2014 #ifdef FEATURE_HISTORY
2018 /* free GetEnvVar's buffer */
2021 /* Remove ctrl break handler */
2022 RemoveBreakHandler();
2024 /* Restore the default console mode */
2025 SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE
),
2026 ENABLE_PROCESSED_INPUT
| ENABLE_LINE_INPUT
| ENABLE_ECHO_INPUT
);
2027 SetConsoleMode(GetStdHandle(STD_OUTPUT_HANDLE
),
2028 ENABLE_PROCESSED_OUTPUT
| ENABLE_WRAP_AT_EOL_OUTPUT
);
2030 DeleteCriticalSection(&ChildProcessRunningLock
);
2036 int _tmain(int argc
, const TCHAR
*argv
[])
2038 TCHAR startPath
[MAX_PATH
];
2040 InitializeCriticalSection(&ChildProcessRunningLock
);
2041 lpOriginalEnvironment
= DuplicateEnvironment();
2043 GetCurrentDirectory(ARRAYSIZE(startPath
), startPath
);
2047 InputCodePage
= GetConsoleCP();
2048 OutputCodePage
= GetConsoleOutputCP();
2050 CMD_ModuleHandle
= GetModuleHandle(NULL
);
2052 /* Perform general initialization, parse switches on command-line */
2055 /* Call prompt routine */
2058 /* Do the cleanup */
2061 cmd_free(lpOriginalEnvironment
);
2063 cmd_exit(nErrorLevel
);