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>
148 typedef NTSTATUS (WINAPI
*NtQueryInformationProcessProc
)(HANDLE
, PROCESSINFOCLASS
,
149 PVOID
, ULONG
, PULONG
);
150 typedef NTSTATUS (WINAPI
*NtReadVirtualMemoryProc
)(HANDLE
, PVOID
, PVOID
, SIZE_T
, PSIZE_T
);
152 BOOL bExit
= FALSE
; /* Indicates EXIT was typed */
153 BOOL bCanExit
= TRUE
; /* Indicates if this shell is exitable */
154 BOOL bCtrlBreak
= FALSE
; /* Ctrl-Break or Ctrl-C hit */
155 BOOL bIgnoreEcho
= FALSE
; /* Set this to TRUE to prevent a newline, when executing a command */
156 static BOOL fSingleCommand
= 0; /* When we are executing something passed on the command line after /C or /K */
157 static BOOL bAlwaysStrip
= FALSE
;
158 INT nErrorLevel
= 0; /* Errorlevel of last launched external program */
159 CRITICAL_SECTION ChildProcessRunningLock
;
160 BOOL bDisableBatchEcho
= FALSE
;
161 BOOL bEnableExtensions
= TRUE
;
162 BOOL bDelayedExpansion
= FALSE
;
163 DWORD dwChildProcessId
= 0;
164 LPTSTR lpOriginalEnvironment
;
165 HANDLE CMD_ModuleHandle
;
167 BOOL bTitleSet
= FALSE
; /* Indicates whether the console title has been changed and needs to be restored later */
168 TCHAR szCurTitle
[MAX_PATH
];
170 static NtQueryInformationProcessProc NtQueryInformationProcessPtr
= NULL
;
171 static NtReadVirtualMemoryProc NtReadVirtualMemoryPtr
= NULL
;
174 * Default output file stream translation mode is UTF8, but CMD switches
175 * allow to change it to either UTF16 (/U) or ANSI (/A).
177 CON_STREAM_MODE OutputStreamMode
= UTF8Text
; // AnsiText;
179 #ifdef INCLUDE_CMD_COLOR
180 WORD wDefColor
= 0; /* Default color */
186 * insert commas into a number
189 ConvertULargeInteger(ULONGLONG num
, LPTSTR des
, UINT len
, BOOL bPutSeparator
)
191 TCHAR temp
[39]; /* maximum length with nNumberGroups == 1 */
198 iTarget
= nNumberGroups
;
200 bPutSeparator
= FALSE
;
204 if (iTarget
== n
&& bPutSeparator
)
206 iTarget
+= nNumberGroups
+ 1;
207 temp
[38 - n
++] = cThousandSeparator
;
209 temp
[38 - n
++] = (TCHAR
)(num
% 10) + _T('0');
215 memcpy(des
, temp
+ 39 - n
, n
* sizeof(TCHAR
));
222 * Is a process a console process?
224 static BOOL
IsConsoleProcess(HANDLE Process
)
227 PROCESS_BASIC_INFORMATION Info
;
231 if (NULL
== NtQueryInformationProcessPtr
|| NULL
== NtReadVirtualMemoryPtr
)
236 Status
= NtQueryInformationProcessPtr (
237 Process
, ProcessBasicInformation
,
238 &Info
, sizeof(PROCESS_BASIC_INFORMATION
), NULL
);
239 if (! NT_SUCCESS(Status
))
241 WARN ("NtQueryInformationProcess failed with status %08x\n", Status
);
244 Status
= NtReadVirtualMemoryPtr (
245 Process
, Info
.PebBaseAddress
, &ProcessPeb
,
246 sizeof(PEB
), &BytesRead
);
247 if (! NT_SUCCESS(Status
) || sizeof(PEB
) != BytesRead
)
249 WARN ("Couldn't read virt mem status %08x bytes read %Iu\n", Status
, BytesRead
);
253 return IMAGE_SUBSYSTEM_WINDOWS_CUI
== ProcessPeb
.ImageSubsystem
;
259 #define SHELLEXECUTETEXT "ShellExecuteExW"
261 #define SHELLEXECUTETEXT "ShellExecuteExA"
264 typedef BOOL (WINAPI
*MYEX
)(LPSHELLEXECUTEINFO lpExecInfo
);
266 HANDLE
RunFile(DWORD flags
, LPTSTR filename
, LPTSTR params
,
267 LPTSTR directory
, INT show
)
269 SHELLEXECUTEINFO sei
;
274 TRACE ("RunFile(%s)\n", debugstr_aw(filename
));
275 hShell32
= LoadLibrary(_T("SHELL32.DLL"));
278 WARN ("RunFile: couldn't load SHELL32.DLL!\n");
282 hShExt
= (MYEX
)(FARPROC
)GetProcAddress(hShell32
, SHELLEXECUTETEXT
);
285 WARN ("RunFile: couldn't find ShellExecuteExA/W in SHELL32.DLL!\n");
286 FreeLibrary(hShell32
);
290 TRACE ("RunFile: ShellExecuteExA/W is at %x\n", hShExt
);
292 memset(&sei
, 0, sizeof sei
);
293 sei
.cbSize
= sizeof sei
;
295 sei
.lpFile
= filename
;
296 sei
.lpParameters
= params
;
297 sei
.lpDirectory
= directory
;
301 TRACE ("RunFile: ShellExecuteExA/W returned 0x%p\n", ret
);
303 FreeLibrary(hShell32
);
304 return ret
? sei
.hProcess
: NULL
;
309 SetConTitle(LPCTSTR pszTitle
)
311 TCHAR szNewTitle
[MAX_PATH
];
316 /* Don't do anything if we run inside a batch file, or we are just running a single command */
317 if (bc
|| (fSingleCommand
== 1))
320 /* Save the original console title and build a new one */
321 GetConsoleTitle(szCurTitle
, ARRAYSIZE(szCurTitle
));
322 StringCchPrintf(szNewTitle
, ARRAYSIZE(szNewTitle
),
323 _T("%s - %s"), szCurTitle
, pszTitle
);
325 ConSetTitle(szNewTitle
);
331 /* Restore the original console title */
332 if (!bc
&& bTitleSet
)
334 ConSetTitle(szCurTitle
);
340 * This command (in First) was not found in the command table
342 * Full - output buffer to hold whole command line
343 * First - first word on command line
344 * Rest - rest of command line
347 Execute(LPTSTR Full
, LPTSTR First
, LPTSTR Rest
, PARSED_COMMAND
*Cmd
)
349 TCHAR
*first
, *rest
, *dot
;
350 DWORD dwExitCode
= 0;
352 TCHAR szFullName
[MAX_PATH
];
353 TCHAR szFullCmdLine
[CMDLINE_LENGTH
];
355 TRACE ("Execute: \'%s\' \'%s\'\n", debugstr_aw(First
), debugstr_aw(Rest
));
357 /* Though it was already parsed once, we have a different set of rules
358 for parsing before we pass to CreateProcess */
359 if (First
[0] == _T('/') || (First
[0] && First
[1] == _T(':')))
361 /* Use the entire first word as the program name (no change) */
362 FirstEnd
= First
+ _tcslen(First
);
366 /* If present in the first word, spaces and ,;=/ end the program
367 * name and become the beginning of its parameters. */
368 BOOL bInside
= FALSE
;
369 for (FirstEnd
= First
; *FirstEnd
; FirstEnd
++)
371 if (!bInside
&& (_istspace(*FirstEnd
) || _tcschr(_T(",;=/"), *FirstEnd
)))
373 bInside
^= *FirstEnd
== _T('"');
377 /* Copy the new first/rest into the buffer */
378 rest
= &Full
[FirstEnd
- First
+ 1];
379 _tcscpy(rest
, FirstEnd
);
382 *FirstEnd
= _T('\0');
383 _tcscpy(first
, First
);
385 /* check for a drive change */
386 if ((_istalpha (first
[0])) && (!_tcscmp (first
+ 1, _T(":"))))
389 if (!SetCurrentDirectory(first
))
391 /* Guess they changed disc or something, handle that gracefully and get to root */
397 working
= SetCurrentDirectory(str
);
400 if (!working
) ConErrResPuts (STRING_FREE_ERROR1
);
404 /* get the PATH environment variable and parse it */
405 /* search the PATH environment variable for the binary */
407 if (!SearchForExecutable(First
, szFullName
))
409 error_bad_command(first
);
413 /* Set the new console title */
414 FirstEnd
= first
+ (FirstEnd
- First
); /* Point to the separating NULL in the full built string */
418 /* check if this is a .BAT or .CMD file */
419 dot
= _tcsrchr (szFullName
, _T('.'));
420 if (dot
&& (!_tcsicmp (dot
, _T(".bat")) || !_tcsicmp (dot
, _T(".cmd"))))
422 while (*rest
== _T(' '))
425 *FirstEnd
= _T('\0');
426 TRACE ("[BATCH: %s %s]\n", debugstr_aw(szFullName
), debugstr_aw(rest
));
427 dwExitCode
= Batch(szFullName
, first
, rest
, Cmd
);
431 /* exec the program */
432 PROCESS_INFORMATION prci
;
435 /* build command line for CreateProcess(): FullName + " " + rest */
436 BOOL quoted
= !!_tcschr(First
, _T(' '));
437 _tcscpy(szFullCmdLine
, quoted
? _T("\"") : _T(""));
438 _tcsncat(szFullCmdLine
, First
, CMDLINE_LENGTH
- _tcslen(szFullCmdLine
) - 1);
439 _tcsncat(szFullCmdLine
, quoted
? _T("\"") : _T(""), CMDLINE_LENGTH
- _tcslen(szFullCmdLine
) - 1);
443 _tcsncat(szFullCmdLine
, _T(" "), CMDLINE_LENGTH
- _tcslen(szFullCmdLine
) - 1);
444 _tcsncat(szFullCmdLine
, rest
, CMDLINE_LENGTH
- _tcslen(szFullCmdLine
) - 1);
447 TRACE ("[EXEC: %s]\n", debugstr_aw(szFullCmdLine
));
449 /* fill startup info */
450 memset(&stui
, 0, sizeof(stui
));
451 stui
.cb
= sizeof(stui
);
453 stui
.dwFlags
= STARTF_USESHOWWINDOW
;
454 stui
.wShowWindow
= SW_SHOWDEFAULT
;
456 /* Set the console to standard mode */
457 SetConsoleMode(ConStreamGetOSHandle(StdIn
),
458 ENABLE_PROCESSED_INPUT
| ENABLE_LINE_INPUT
| ENABLE_ECHO_INPUT
);
460 if (CreateProcess(szFullName
,
471 CloseHandle(prci
.hThread
);
475 // See if we can run this with ShellExecute() ie myfile.xls
476 prci
.hProcess
= RunFile(SEE_MASK_NOCLOSEPROCESS
| SEE_MASK_NO_CONSOLE
,
483 *FirstEnd
= _T('\0');
485 if (prci
.hProcess
!= NULL
)
487 if (bc
!= NULL
|| fSingleCommand
!= 0 || IsConsoleProcess(prci
.hProcess
))
489 /* when processing a batch file or starting console processes: execute synchronously */
490 EnterCriticalSection(&ChildProcessRunningLock
);
491 dwChildProcessId
= prci
.dwProcessId
;
493 WaitForSingleObject(prci
.hProcess
, INFINITE
);
495 LeaveCriticalSection(&ChildProcessRunningLock
);
497 GetExitCodeProcess(prci
.hProcess
, &dwExitCode
);
498 nErrorLevel
= (INT
)dwExitCode
;
500 CloseHandle(prci
.hProcess
);
504 TRACE ("[ShellExecute failed!: %s]\n", debugstr_aw(Full
));
505 error_bad_command(first
);
509 /* Restore the default console mode */
510 SetConsoleMode(ConStreamGetOSHandle(StdIn
),
511 ENABLE_PROCESSED_INPUT
| ENABLE_LINE_INPUT
| ENABLE_ECHO_INPUT
);
512 SetConsoleMode(ConStreamGetOSHandle(StdOut
),
513 ENABLE_PROCESSED_OUTPUT
| ENABLE_WRAP_AT_EOL_OUTPUT
);
516 /* Update the local code page cache */
518 UINT uNewInputCodePage
= GetConsoleCP();
519 UINT uNewOutputCodePage
= GetConsoleOutputCP();
521 if ((InputCodePage
!= uNewInputCodePage
) ||
522 (OutputCodePage
!= uNewOutputCodePage
))
524 InputCodePage
= uNewInputCodePage
;
525 OutputCodePage
= uNewOutputCodePage
;
527 /* Reset the current thread UI language */
528 if (IsConsoleHandle(ConStreamGetOSHandle(StdOut
)) ||
529 IsConsoleHandle(ConStreamGetOSHandle(StdErr
)))
531 ConSetThreadUILanguage(0);
533 /* Update the streams cached code page */
534 ConStdStreamsSetCacheCodePage(InputCodePage
, OutputCodePage
);
536 /* Update the locale as well */
541 /* Restore the original console title */
549 * Look through the internal commands and determine whether or not this
550 * command is one of them. If it is, call the command. If not, call
551 * execute to run it as an external program.
553 * first - first word on command line
554 * rest - rest of command line
557 DoCommand(LPTSTR first
, LPTSTR rest
, PARSED_COMMAND
*Cmd
)
561 LPTSTR param
; /* Pointer to command's parameters */
564 BOOL nointernal
= FALSE
;
567 TRACE ("DoCommand: (\'%s\' \'%s\')\n", debugstr_aw(first
), debugstr_aw(rest
));
569 /* Full command line */
570 com
= cmd_alloc((_tcslen(first
) + _tcslen(rest
) + 2) * sizeof(TCHAR
));
573 error_out_of_memory();
577 /* If present in the first word, these characters end the name of an
578 * internal command and become the beginning of its parameters. */
579 cp
= first
+ _tcscspn(first
, _T("\t +,/;=[]"));
581 for (cl
= 0; cl
< (cp
- first
); cl
++)
583 /* These characters do it too, but if one of them is present,
584 * then we check to see if the word is a file name and skip
585 * checking for internal commands if so.
586 * This allows running programs with names like "echo.exe" */
587 if (_tcschr(_T(".:\\"), first
[cl
]))
591 nointernal
= IsExistingFile(first
);
597 /* Scan internal command table */
598 for (cmdptr
= cmds
; !nointernal
&& cmdptr
->name
; cmdptr
++)
600 if (!_tcsnicmp(first
, cmdptr
->name
, cl
) && cmdptr
->name
[cl
] == _T('\0'))
606 /* Skip over whitespace to rest of line, exclude 'echo' command */
607 if (_tcsicmp(cmdptr
->name
, _T("echo")) != 0)
609 while (_istspace(*param
))
613 /* Set the new console title */
616 ret
= cmdptr
->func(param
);
618 /* Restore the original console title */
626 ret
= Execute(com
, first
, rest
, Cmd
);
633 * process the command line and execute the appropriate functions
634 * full input/output redirection and piping are supported
636 INT
ParseCommandLine(LPTSTR cmd
)
641 Cmd
= ParseCommand(cmd
);
644 /* Return an adequate error code */
645 return (!bParseError
? 0 : 1);
648 Ret
= ExecuteCommand(Cmd
);
653 /* Execute a command without waiting for it to finish. If it's an internal
654 * command or batch file, we must create a new cmd.exe process to handle it.
655 * TODO: For now, this just always creates a cmd.exe process.
656 * This works, but is inefficient for running external programs,
657 * which could just be run directly. */
659 ExecuteAsync(PARSED_COMMAND
*Cmd
)
661 TCHAR CmdPath
[MAX_PATH
];
662 TCHAR CmdParams
[CMDLINE_LENGTH
], *ParamsEnd
;
664 PROCESS_INFORMATION prci
;
666 /* Get the path to cmd.exe */
667 GetModuleFileName(NULL
, CmdPath
, ARRAYSIZE(CmdPath
));
669 /* Build the parameter string to pass to cmd.exe */
670 ParamsEnd
= _stpcpy(CmdParams
, _T("/S/D/C\""));
671 ParamsEnd
= UnparseCommand(Cmd
, ParamsEnd
, &CmdParams
[CMDLINE_LENGTH
- 2]);
674 error_out_of_memory();
677 _tcscpy(ParamsEnd
, _T("\""));
679 memset(&stui
, 0, sizeof stui
);
680 stui
.cb
= sizeof(STARTUPINFO
);
681 if (!CreateProcess(CmdPath
, CmdParams
, NULL
, NULL
, TRUE
, 0,
682 NULL
, NULL
, &stui
, &prci
))
684 ErrorMessage(GetLastError(), NULL
);
688 CloseHandle(prci
.hThread
);
689 return prci
.hProcess
;
693 ExecutePipeline(PARSED_COMMAND
*Cmd
)
695 #ifdef FEATURE_REDIRECTION
696 HANDLE hInput
= NULL
;
697 HANDLE hOldConIn
= GetStdHandle(STD_INPUT_HANDLE
);
698 HANDLE hOldConOut
= GetStdHandle(STD_OUTPUT_HANDLE
);
699 HANDLE hProcess
[MAXIMUM_WAIT_OBJECTS
];
703 /* Do all but the last pipe command */
706 HANDLE hPipeRead
, hPipeWrite
;
707 if (nProcesses
> (MAXIMUM_WAIT_OBJECTS
- 2))
709 error_too_many_parameters(_T("|"));
713 /* Create the pipe that this process will write into.
714 * Make the handles non-inheritable initially, because this
715 * process shouldn't inherit the reading handle. */
716 if (!CreatePipe(&hPipeRead
, &hPipeWrite
, NULL
, 0))
722 /* The writing side of the pipe is STDOUT for this process */
723 SetHandleInformation(hPipeWrite
, HANDLE_FLAG_INHERIT
, HANDLE_FLAG_INHERIT
);
724 SetStdHandle(STD_OUTPUT_HANDLE
, hPipeWrite
);
726 /* Execute it (error check is done later for easier cleanup) */
727 hProcess
[nProcesses
] = ExecuteAsync(Cmd
->Subcommands
);
728 CloseHandle(hPipeWrite
);
732 /* The reading side of the pipe will be STDIN for the next process */
733 SetHandleInformation(hPipeRead
, HANDLE_FLAG_INHERIT
, HANDLE_FLAG_INHERIT
);
734 SetStdHandle(STD_INPUT_HANDLE
, hPipeRead
);
737 if (!hProcess
[nProcesses
])
741 Cmd
= Cmd
->Subcommands
->Next
;
742 } while (Cmd
->Type
== C_PIPE
);
744 /* The last process uses the original STDOUT */
745 SetStdHandle(STD_OUTPUT_HANDLE
, hOldConOut
);
746 hProcess
[nProcesses
] = ExecuteAsync(Cmd
);
747 if (!hProcess
[nProcesses
])
751 SetStdHandle(STD_INPUT_HANDLE
, hOldConIn
);
753 /* Wait for all processes to complete */
754 EnterCriticalSection(&ChildProcessRunningLock
);
755 WaitForMultipleObjects(nProcesses
, hProcess
, TRUE
, INFINITE
);
756 LeaveCriticalSection(&ChildProcessRunningLock
);
758 /* Use the exit code of the last process in the pipeline */
759 GetExitCodeProcess(hProcess
[nProcesses
- 1], &dwExitCode
);
760 nErrorLevel
= (INT
)dwExitCode
;
762 while (--nProcesses
>= 0)
763 CloseHandle(hProcess
[nProcesses
]);
769 while (--nProcesses
>= 0)
771 TerminateProcess(hProcess
[nProcesses
], 0);
772 CloseHandle(hProcess
[nProcesses
]);
774 SetStdHandle(STD_INPUT_HANDLE
, hOldConIn
);
775 SetStdHandle(STD_OUTPUT_HANDLE
, hOldConOut
);
783 IN PARSED_COMMAND
*Cmd
)
786 (bc && bc->current == NULL)
792 /* If we don't have any command, or if this is REM, ignore it */
793 if (!Cmd
|| (Cmd
->Type
== C_REM
))
796 * Do not execute any command if we are about to exit CMD, or about to
797 * change batch execution context, e.g. in case of a CALL / GOTO / EXIT.
799 if (bExit
|| SeenGoto())
802 if (!PerformRedirection(Cmd
->Redirections
))
809 First
= DoDelayedExpansion(Cmd
->Command
.First
);
812 Rest
= DoDelayedExpansion(Cmd
->Command
.Rest
);
815 Ret
= DoCommand(First
, Rest
, Cmd
);
827 for (Sub
= Cmd
->Subcommands
; Sub
&& !SeenGoto(); Sub
= Sub
->Next
)
828 Ret
= ExecuteCommand(Sub
);
832 Sub
= Cmd
->Subcommands
;
833 Ret
= ExecuteCommand(Sub
);
834 if ((Ret
!= 0) && !SeenGoto())
837 Ret
= ExecuteCommand(Sub
->Next
);
842 Sub
= Cmd
->Subcommands
;
843 Ret
= ExecuteCommand(Sub
);
844 if ((Ret
== 0) && !SeenGoto())
845 Ret
= ExecuteCommand(Sub
->Next
);
849 Ret
= ExecutePipeline(Cmd
);
853 Ret
= ExecuteFor(Cmd
);
857 Ret
= ExecuteIf(Cmd
);
861 UndoRedirection(Cmd
->Redirections
, NULL
);
868 ExecuteCommandWithEcho(
869 IN PARSED_COMMAND
*Cmd
)
871 /* Echo the reconstructed command line */
872 if (bEcho
&& !bDisableBatchEcho
&& Cmd
&& (Cmd
->Type
!= C_QUIET
))
875 ConOutChar(_T('\n'));
878 ConOutChar(_T('\n'));
881 /* Run the command */
882 return ExecuteCommand(Cmd
);
886 GetEnvVar(LPCTSTR varName
)
888 static LPTSTR ret
= NULL
;
893 size
= GetEnvironmentVariable(varName
, NULL
, 0);
896 ret
= cmd_alloc(size
* sizeof(TCHAR
));
898 GetEnvironmentVariable(varName
, ret
, size
+ 1);
904 GetEnvVarOrSpecial(LPCTSTR varName
)
906 static TCHAR ret
[MAX_PATH
];
908 LPTSTR var
= GetEnvVar(varName
);
912 /* The environment variable doesn't exist, look for
913 * a "special" one only if extensions are enabled. */
914 if (!bEnableExtensions
)
918 if (_tcsicmp(varName
, _T("CD")) == 0)
920 GetCurrentDirectory(ARRAYSIZE(ret
), ret
);
924 else if (_tcsicmp(varName
, _T("DATE")) == 0)
926 return GetDateString();
929 else if (_tcsicmp(varName
, _T("TIME")) == 0)
931 return GetTimeString();
934 else if (_tcsicmp(varName
, _T("RANDOM")) == 0)
936 /* Get random number */
937 _itot(rand(), ret
, 10);
941 else if (_tcsicmp(varName
, _T("CMDCMDLINE")) == 0)
943 return GetCommandLine();
945 /* %CMDEXTVERSION% */
946 else if (_tcsicmp(varName
, _T("CMDEXTVERSION")) == 0)
948 /* Set Command Extensions version number to CMDEXTVERSION */
949 _itot(CMDEXTVERSION
, ret
, 10);
953 else if (_tcsicmp(varName
, _T("ERRORLEVEL")) == 0)
955 _itot(nErrorLevel
, ret
, 10);
958 #if (NTDDI_VERSION >= NTDDI_WIN7)
959 /* Available in Win7+, even if the underlying API is available in Win2003+ */
960 /* %HIGHESTNUMANODENUMBER% */
961 else if (_tcsicmp(varName
, _T("HIGHESTNUMANODENUMBER")) == 0)
963 ULONG NumaNodeNumber
= 0;
964 GetNumaHighestNodeNumber(&NumaNodeNumber
);
965 _itot(NumaNodeNumber
, ret
, 10);
973 /* Handle the %~var syntax */
976 IN OUT PCTSTR
* pFormat
,
977 IN
BOOL (*GetVar
)(TCHAR
, PCTSTR
*, BOOL
*))
979 static const TCHAR ModifierTable
[] = _T("dpnxfsatz");
981 M_DRIVE
= 1, /* D: drive letter */
982 M_PATH
= 2, /* P: path */
983 M_NAME
= 4, /* N: filename */
984 M_EXT
= 8, /* X: extension */
985 M_FULL
= 16, /* F: full path (drive+path+name+ext) */
986 M_SHORT
= 32, /* S: full path (drive+path+name+ext), use short names */
987 M_ATTR
= 64, /* A: attributes */
988 M_TIME
= 128, /* T: modification time */
989 M_SIZE
= 256, /* Z: file size */
992 PCTSTR Format
, FormatEnd
;
993 PCTSTR PathVarName
= NULL
;
996 BOOL VariableIsParam0
;
997 TCHAR FullPath
[MAX_PATH
];
998 TCHAR FixedPath
[MAX_PATH
];
999 PTCHAR Filename
, Extension
;
1001 WIN32_FIND_DATA w32fd
;
1004 static TCHAR Result
[CMDLINE_LENGTH
];
1006 /* Check whether the current character is a recognized variable.
1007 * If it is not, then restore the previous one: there is indeed
1008 * ambiguity between modifier characters and FOR variables;
1009 * the rule that CMD uses is to pick the longest possible match.
1010 * This case can happen if we have a FOR-variable specification
1011 * of the following form:
1013 * %~<modifiers><actual FOR variable character><other characters>
1015 * where the FOR variable character is also a similar to a modifier,
1016 * but should not be interpreted as is, and the following other
1017 * characters are not part of the possible modifier characters, and
1018 * are unrelated to the FOR variable (they can be part of a command).
1019 * For example, if there is a %n variable, then out of %~anxnd,
1020 * %~anxn will be substituted rather than just %~an.
1022 * In the following examples, all characters 'd','p','n','x' are valid modifiers.
1024 * 1. In this example, the FOR variable character is 'x' and the actual
1025 * modifiers are 'dpn'. Parsing will first determine that 'dpnx'
1026 * are modifiers, with the possible (last) valid variable being 'x',
1027 * and will stop at the letter 'g'. Since 'g' is not a valid
1028 * variable, then the actual variable is the lattest one 'x',
1029 * and the modifiers are then actually 'dpn'.
1030 * The FOR-loop will then display the %x variable formatted with 'dpn'
1031 * and will append any other characters following, 'g'.
1033 * C:\Temp>for %x in (foo.exe bar.txt) do @echo %~dpnxg
1038 * 2. In this second example, the FOR variable character is 'g' and
1039 * the actual modifiers are 'dpnx'. Parsing will determine also that
1040 * the possible (last) valid variable could be 'x', but since it's
1041 * not present in the FOR-variables list, it won't be the case.
1042 * This means that the actual FOR variable character must follow,
1043 * in this case, 'g'.
1045 * C:\Temp>for %g in (foo.exe bar.txt) do @echo %~dpnxg
1050 /* First, go through as many modifier characters as possible */
1051 FormatEnd
= Format
= *pFormat
;
1052 while (*FormatEnd
&& _tcschr(ModifierTable
, _totlower(*FormatEnd
)))
1055 if (*FormatEnd
== _T('$'))
1058 PathVarName
= FormatEnd
+ 1;
1059 FormatEnd
= _tcschr(PathVarName
, _T(':'));
1063 /* Must be immediately followed by the variable */
1064 if (!GetVar(*++FormatEnd
, &Variable
, &VariableIsParam0
))
1069 /* Backtrack if necessary to get a variable name match */
1070 while (!GetVar(*FormatEnd
, &Variable
, &VariableIsParam0
))
1072 if (FormatEnd
== Format
)
1078 *pFormat
= FormatEnd
+ 1;
1080 /* If the variable is empty, return an empty string */
1081 if (!Variable
|| !*Variable
)
1084 /* Exclude the leading and trailing quotes */
1085 VarEnd
= &Variable
[_tcslen(Variable
)];
1086 if (*Variable
== _T('"'))
1089 if (VarEnd
> Variable
&& VarEnd
[-1] == _T('"'))
1093 if ((ULONG_PTR
)VarEnd
- (ULONG_PTR
)Variable
>= sizeof(Result
))
1095 memcpy(Result
, Variable
, (ULONG_PTR
)VarEnd
- (ULONG_PTR
)Variable
);
1096 Result
[VarEnd
- Variable
] = _T('\0');
1098 /* Now determine the actual modifiers */
1099 for (; Format
< FormatEnd
&& *Format
!= _T('$'); ++Format
)
1100 Modifiers
|= 1 << (_tcschr(ModifierTable
, _totlower(*Format
)) - ModifierTable
);
1104 /* $PATH: syntax - search the directories listed in the
1105 * specified environment variable for the file */
1107 ((PTSTR
)FormatEnd
)[-1] = _T('\0'); // FIXME: HACK!
1108 PathVar
= GetEnvVar(PathVarName
);
1109 ((PTSTR
)FormatEnd
)[-1] = _T(':');
1111 !SearchPath(PathVar
, Result
, NULL
, ARRAYSIZE(FullPath
), FullPath
, NULL
))
1116 else if (Modifiers
== 0)
1118 /* For plain %~var with no modifiers, just return the variable without quotes */
1121 else if (VariableIsParam0
)
1123 /* Special case: If the variable is %0 and modifier characters are present,
1124 * use the batch file's path (which includes the .bat/.cmd extension)
1125 * rather than the actual %0 variable (which might not). */
1127 _tcscpy(FullPath
, bc
->BatchFilePath
);
1131 /* Convert the variable, now without quotes, to a full path */
1132 if (!GetFullPathName(Result
, ARRAYSIZE(FullPath
), FullPath
, NULL
))
1136 /* Next step is to change the path to fix letter case (e.g.
1137 * C:\ReAcToS -> C:\ReactOS) and, if requested with the S modifier,
1138 * replace long filenames with short. */
1143 /* Copy drive letter */
1147 /* Loop over each \-separated component in the path */
1149 TCHAR
*Next
= _tcschr(In
, _T('\\'));
1152 /* Use FindFirstFile to get the correct name */
1153 if (Out
+ _tcslen(In
) + 1 >= &FixedPath
[ARRAYSIZE(FixedPath
)])
1156 hFind
= FindFirstFile(FixedPath
, &w32fd
);
1157 /* If it doesn't exist, just leave the name as it was given */
1158 if (hFind
!= INVALID_HANDLE_VALUE
)
1160 PTSTR FixedComponent
= w32fd
.cFileName
;
1161 if ((Modifiers
& M_SHORT
) && *w32fd
.cAlternateFileName
)
1162 FixedComponent
= w32fd
.cAlternateFileName
;
1166 if (Out
+ _tcslen(FixedComponent
) + 1 >= &FixedPath
[ARRAYSIZE(FixedPath
)])
1168 _tcscpy(Out
, FixedComponent
);
1171 Out
+= _tcslen(Out
);
1175 } while (In
!= NULL
);
1178 /* Build the result string. Start with attributes, modification time, and
1179 * file size. If the file didn't exist, these fields will all be empty. */
1181 if (hFind
!= INVALID_HANDLE_VALUE
)
1183 if (Modifiers
& M_ATTR
)
1185 static const struct {
1188 } *Attrib
, Table
[] = {
1189 { _T('d'), FILE_ATTRIBUTE_DIRECTORY
},
1190 { _T('r'), FILE_ATTRIBUTE_READONLY
},
1191 { _T('a'), FILE_ATTRIBUTE_ARCHIVE
},
1192 { _T('h'), FILE_ATTRIBUTE_HIDDEN
},
1193 { _T('s'), FILE_ATTRIBUTE_SYSTEM
},
1194 { _T('c'), FILE_ATTRIBUTE_COMPRESSED
},
1195 { _T('o'), FILE_ATTRIBUTE_OFFLINE
},
1196 { _T('t'), FILE_ATTRIBUTE_TEMPORARY
},
1197 { _T('l'), FILE_ATTRIBUTE_REPARSE_POINT
},
1198 #if (NTDDI_VERSION >= NTDDI_WIN8)
1199 { _T('v'), FILE_ATTRIBUTE_INTEGRITY_STREAM
},
1200 { _T('x'), FILE_ATTRIBUTE_NO_SCRUB_DATA
/* 0x20000 */ },
1203 for (Attrib
= Table
; Attrib
!= &Table
[ARRAYSIZE(Table
)]; Attrib
++)
1205 *Out
++ = w32fd
.dwFileAttributes
& Attrib
->Value
1211 if (Modifiers
& M_TIME
)
1215 FileTimeToLocalFileTime(&w32fd
.ftLastWriteTime
, &ft
);
1216 FileTimeToSystemTime(&ft
, &st
);
1218 Out
+= FormatDate(Out
, &st
, TRUE
);
1220 Out
+= FormatTime(Out
, &st
);
1223 if (Modifiers
& M_SIZE
)
1225 ULARGE_INTEGER Size
;
1226 Size
.LowPart
= w32fd
.nFileSizeLow
;
1227 Size
.HighPart
= w32fd
.nFileSizeHigh
;
1228 Out
+= _stprintf(Out
, _T("%I64u "), Size
.QuadPart
);
1232 /* When using the path-searching syntax or the S modifier,
1233 * at least part of the file path is always included.
1234 * If none of the DPNX modifiers are present, include the full path */
1235 if (PathVarName
|| (Modifiers
& M_SHORT
))
1236 if ((Modifiers
& (M_DRIVE
| M_PATH
| M_NAME
| M_EXT
)) == 0)
1237 Modifiers
|= M_FULL
;
1239 /* Now add the requested parts of the name.
1240 * With the F modifier, add all parts to form the full path. */
1241 Extension
= _tcsrchr(Filename
, _T('.'));
1242 if (Modifiers
& (M_DRIVE
| M_FULL
))
1244 *Out
++ = FixedPath
[0];
1245 *Out
++ = FixedPath
[1];
1247 if (Modifiers
& (M_PATH
| M_FULL
))
1249 memcpy(Out
, &FixedPath
[2], (ULONG_PTR
)Filename
- (ULONG_PTR
)&FixedPath
[2]);
1250 Out
+= Filename
- &FixedPath
[2];
1252 if (Modifiers
& (M_NAME
| M_FULL
))
1254 while (*Filename
&& Filename
!= Extension
)
1255 *Out
++ = *Filename
++;
1257 if (Modifiers
& (M_EXT
| M_FULL
))
1260 Out
= _stpcpy(Out
, Extension
);
1263 /* Trim trailing space which otherwise would appear as a
1264 * result of using the A/T/Z modifiers but no others. */
1265 while (Out
!= &Result
[0] && Out
[-1] == _T(' '))
1275 OUT PUINT varNameLen
)
1286 varNameEnd
= varName
+ 1;
1287 ret
= GetEnhancedVar(&varNameEnd
, FindArg
);
1290 ParseErrorEx(varName
);
1293 *varNameLen
= varNameEnd
- varName
;
1309 if (!FindArg(*varName
, &ret
, &dummy
))
1316 /* Copy over the raw params (not including the batch file name) */
1317 return bc
->raw_params
;
1328 OUT
size_t* SrcIncLen
, // VarNameLen
1331 OUT
size_t* DestIncLen
,
1334 #define APPEND(From, Length) \
1336 if (Dest + (Length) > DestEnd) \
1338 memcpy(Dest, (From), (Length) * sizeof(TCHAR)); \
1342 #define APPEND1(Char) \
1344 if (Dest >= DestEnd) \
1350 PCTSTR Start
, End
, SubstStart
;
1366 /* If we are already at the end of the string, fail the substitution */
1368 if (!*Src
|| *Src
== _T('\r') || *Src
== _T('\n'))
1371 if (bc
&& Delim
== _T('%'))
1374 Var
= GetBatchVar(Src
, &NameLen
);
1375 if (!Var
&& bParseError
)
1377 /* Return the partially-parsed command to be
1378 * echoed for error diagnostics purposes. */
1380 APPEND(Src
, _tcslen(Src
) + 1);
1385 VarLength
= _tcslen(Var
);
1386 APPEND(Var
, VarLength
);
1392 /* Find the end of the variable name. A colon (:) will usually
1393 * end the name and begin the optional modifier, but not if it
1394 * is immediately followed by the delimiter (%VAR:%). */
1396 while (*Src
&& *Src
!= Delim
&& !(*Src
== _T(':') && Src
[1] != Delim
))
1400 /* If we are either at the end of the string, or the delimiter
1401 * has been repeated more than once, fail the substitution. */
1402 if (!*Src
|| Src
== SubstStart
)
1406 *(PTSTR
)Src
= _T('\0'); // FIXME: HACK!
1407 Var
= GetEnvVarOrSpecial(SubstStart
);
1408 *(PTSTR
)Src
++ = EndChr
;
1411 /* In a batch context, %NONEXISTENT% "expands" to an
1412 * empty string, otherwise fail the substitution. */
1417 VarLength
= _tcslen(Var
);
1419 if (EndChr
== Delim
)
1421 /* %VAR% - use as-is */
1422 APPEND(Var
, VarLength
);
1424 else if (*Src
== _T('~'))
1426 /* %VAR:~[start][,length]% - Substring.
1427 * Negative values are offsets from the end.
1429 SSIZE_T Start
= _tcstol(Src
+ 1, (PTSTR
*)&Src
, 0);
1430 SSIZE_T End
= (SSIZE_T
)VarLength
;
1433 Start
= min(max(Start
, 0), VarLength
);
1434 if (*Src
== _T(','))
1436 End
= _tcstol(Src
+ 1, (PTSTR
*)&Src
, 0);
1437 End
+= (End
< 0) ? VarLength
: Start
;
1438 End
= min(max(End
, Start
), VarLength
);
1440 if (*Src
++ != Delim
)
1442 APPEND(&Var
[Start
], End
- Start
);
1446 /* %VAR:old=new% - Replace all occurrences of old with new.
1447 * %VAR:*old=new% - Replace first occurrence only,
1448 * and remove everything before it.
1451 size_t OldLength
, NewLength
;
1453 size_t LastMatch
= 0, i
= 0;
1455 if (*Src
== _T('*'))
1461 /* The string to replace may contain the delimiter */
1462 Src
= _tcschr(Old
= Src
, _T('='));
1465 OldLength
= Src
++ - Old
;
1469 Src
= _tcschr(New
= Src
, Delim
);
1472 NewLength
= Src
++ - New
;
1474 while (i
< VarLength
)
1476 if (_tcsnicmp(&Var
[i
], Old
, OldLength
) == 0)
1479 APPEND(&Var
[LastMatch
], i
- LastMatch
);
1480 APPEND(New
, NewLength
);
1489 APPEND(&Var
[LastMatch
], VarLength
- LastMatch
);
1493 *SrcIncLen
= (Src
- Start
);
1494 *DestIncLen
= (Dest
- End
);
1499 /* Only if no batch context active do we echo the delimiter */
1505 ConOutResPrintf(STRING_ALIAS_ERROR
);
1519 #define APPEND(From, Length) \
1521 if (Dest + (Length) > DestEnd) \
1523 memcpy(Dest, (From), (Length) * sizeof(TCHAR)); \
1527 #define APPEND1(Char) \
1529 if (Dest >= DestEnd) \
1534 PTCHAR DestEnd
= Dest
+ CMDLINE_LENGTH
- 1;
1536 size_t SrcIncLen
, DestIncLen
;
1538 while (*Src
/* && (Dest < DestEnd) */)
1542 End
= _tcschr(Src
, Delim
);
1544 End
= Src
+ _tcslen(Src
);
1545 APPEND(Src
, End
- Src
);
1550 if (!SubstituteVar(Src
, &SrcIncLen
, Dest
, DestEnd
, &DestIncLen
, Delim
))
1564 ConOutResPrintf(STRING_ALIAS_ERROR
);
1572 /* Search the list of FOR contexts for a variable */
1584 for (Ctx
= fc
; Ctx
!= NULL
; Ctx
= Ctx
->prev
)
1586 if ((UINT
)(Var
- Ctx
->firstvar
) < Ctx
->varcount
)
1588 *VarPtr
= Ctx
->values
[Var
- Ctx
->firstvar
];
1600 PTCHAR DestEnd
= &Dest
[CMDLINE_LENGTH
- 1];
1603 if (Src
[0] == _T('%'))
1606 PCTSTR End
= &Src
[2];
1607 PCTSTR Value
= NULL
;
1609 if (Src
[1] == _T('~'))
1610 Value
= GetEnhancedVar(&End
, FindForVar
);
1612 if (!Value
&& Src
[1])
1614 if (FindForVar(Src
[1], &Value
, &Dummy
) && !Value
)
1616 /* The variable is empty, return an empty string */
1623 if (Dest
+ _tcslen(Value
) > DestEnd
)
1625 Dest
= _stpcpy(Dest
, Value
);
1630 /* Not a variable; just copy the character */
1631 if (Dest
>= DestEnd
)
1643 TCHAR Buf1
[CMDLINE_LENGTH
];
1644 TCHAR Buf2
[CMDLINE_LENGTH
];
1646 PTCHAR DestEnd
= Buf2
+ CMDLINE_LENGTH
- 1;
1647 size_t SrcIncLen
, DestIncLen
;
1649 /* First, substitute FOR variables */
1650 if (!SubstituteForVars(Line
, Buf1
))
1653 if (!bDelayedExpansion
|| !_tcschr(Buf1
, _T('!')))
1654 return cmd_dup(Buf1
);
1657 * Delayed substitutions are not actually completely the same as
1658 * immediate substitutions. In particular, it is possible to escape
1659 * the exclamation point using the escape caret.
1663 * Perform delayed expansion: expand variables around '!',
1664 * and reparse escape carets.
1667 #define APPEND1(Char) \
1669 if (Dst >= DestEnd) \
1676 while (*Src
&& (Src
< &Buf1
[CMDLINE_LENGTH
]))
1678 if (*Src
== _T('^'))
1681 if (!*Src
|| !(Src
< &Buf1
[CMDLINE_LENGTH
]))
1686 else if (*Src
== _T('!'))
1688 if (!SubstituteVar(Src
, &SrcIncLen
, Dst
, DestEnd
, &DestIncLen
, _T('!')))
1690 return NULL
; // Got an error during parsing.
1706 return cmd_dup(Buf2
);
1709 ConOutResPrintf(STRING_ALIAS_ERROR
);
1718 * Do the prompt/input/process loop.
1721 ReadLine(TCHAR
*commandline
, BOOL bMore
)
1723 TCHAR readline
[CMDLINE_LENGTH
];
1726 /* if no batch input then... */
1731 ConOutResPrintf(STRING_MORE
);
1735 /* JPP 19980807 - if echo off, don't print prompt */
1739 ConOutChar(_T('\n'));
1744 if (!ReadCommand(readline
, CMDLINE_LENGTH
- 1))
1750 if (readline
[0] == _T('\0'))
1751 ConOutChar(_T('\n'));
1753 if (CheckCtrlBreak(BREAK_INPUT
))
1756 if (readline
[0] == _T('\0'))
1763 ip
= ReadBatchLine();
1768 return SubstituteVars(ip
, commandline
, _T('%'));
1775 PARSED_COMMAND
*Cmd
;
1777 while (!bCanExit
|| !bExit
)
1779 /* Reset the Ctrl-Break / Ctrl-C state */
1782 Cmd
= ParseCommand(NULL
);
1786 Ret
= ExecuteCommand(Cmd
);
1795 * Control-break handler.
1799 BreakHandler(IN DWORD dwCtrlType
)
1804 if ((dwCtrlType
!= CTRL_C_EVENT
) &&
1805 (dwCtrlType
!= CTRL_BREAK_EVENT
))
1810 if (!TryEnterCriticalSection(&ChildProcessRunningLock
))
1812 /* Child process is running and will have received the control event */
1817 LeaveCriticalSection(&ChildProcessRunningLock
);
1822 rec
.EventType
= KEY_EVENT
;
1823 rec
.Event
.KeyEvent
.bKeyDown
= TRUE
;
1824 rec
.Event
.KeyEvent
.wRepeatCount
= 1;
1825 rec
.Event
.KeyEvent
.wVirtualKeyCode
= _T('C');
1826 rec
.Event
.KeyEvent
.wVirtualScanCode
= _T('C') - 35;
1827 rec
.Event
.KeyEvent
.uChar
.AsciiChar
= _T('C');
1828 rec
.Event
.KeyEvent
.uChar
.UnicodeChar
= _T('C');
1829 rec
.Event
.KeyEvent
.dwControlKeyState
= RIGHT_CTRL_PRESSED
;
1831 WriteConsoleInput(ConStreamGetOSHandle(StdIn
),
1836 /* FIXME: Handle batch files */
1838 // ConOutPrintf(_T("^C"));
1844 VOID
AddBreakHandler(VOID
)
1846 SetConsoleCtrlHandler(BreakHandler
, TRUE
);
1850 VOID
RemoveBreakHandler(VOID
)
1852 SetConsoleCtrlHandler(BreakHandler
, FALSE
);
1857 * Show commands and options that are available.
1863 /* print command list */
1864 ConOutResPuts(STRING_CMD_HELP1
);
1867 /* print feature list */
1868 ConOutResPuts(STRING_CMD_HELP2
);
1870 #ifdef FEATURE_ALIASES
1871 ConOutResPuts(STRING_CMD_HELP3
);
1873 #ifdef FEATURE_HISTORY
1874 ConOutResPuts(STRING_CMD_HELP4
);
1876 #ifdef FEATURE_UNIX_FILENAME_COMPLETION
1877 ConOutResPuts(STRING_CMD_HELP5
);
1879 #ifdef FEATURE_DIRECTORY_STACK
1880 ConOutResPuts(STRING_CMD_HELP6
);
1882 #ifdef FEATURE_REDIRECTION
1883 ConOutResPuts(STRING_CMD_HELP7
);
1885 ConOutChar(_T('\n'));
1891 LoadRegistrySettings(HKEY hKeyRoot
)
1897 * Buffer big enough to hold the string L"4294967295",
1898 * corresponding to the literal 0xFFFFFFFF (MAXULONG) in decimal.
1902 lRet
= RegOpenKeyEx(hKeyRoot
,
1903 _T("Software\\Microsoft\\Command Processor"),
1907 if (lRet
!= ERROR_SUCCESS
)
1910 #ifdef INCLUDE_CMD_COLOR
1911 len
= sizeof(Buffer
);
1912 lRet
= RegQueryValueEx(hKey
,
1918 if (lRet
== ERROR_SUCCESS
)
1920 /* Overwrite the default attributes */
1921 if (dwType
== REG_DWORD
)
1922 wDefColor
= (WORD
)*(PDWORD
)Buffer
;
1923 else if (dwType
== REG_SZ
)
1924 wDefColor
= (WORD
)_tcstol((PTSTR
)Buffer
, NULL
, 0);
1926 // else, use the default attributes retrieved before.
1930 len
= sizeof(Buffer
);
1931 lRet
= RegQueryValueEx(hKey
,
1932 _T("DisableUNCCheck"),
1937 if (lRet
== ERROR_SUCCESS
)
1939 /* Overwrite the default setting */
1940 if (dwType
== REG_DWORD
)
1941 bDisableUNCCheck
= !!*(PDWORD
)Buffer
;
1942 else if (dwType
== REG_SZ
)
1943 bDisableUNCCheck
= (_ttol((PTSTR
)Buffer
) == 1);
1945 // else, use the default setting set globally.
1948 len
= sizeof(Buffer
);
1949 lRet
= RegQueryValueEx(hKey
,
1950 _T("DelayedExpansion"),
1955 if (lRet
== ERROR_SUCCESS
)
1957 /* Overwrite the default setting */
1958 if (dwType
== REG_DWORD
)
1959 bDelayedExpansion
= !!*(PDWORD
)Buffer
;
1960 else if (dwType
== REG_SZ
)
1961 bDelayedExpansion
= (_ttol((PTSTR
)Buffer
) == 1);
1963 // else, use the default setting set globally.
1965 len
= sizeof(Buffer
);
1966 lRet
= RegQueryValueEx(hKey
,
1967 _T("EnableExtensions"),
1972 if (lRet
== ERROR_SUCCESS
)
1974 /* Overwrite the default setting */
1975 if (dwType
== REG_DWORD
)
1976 bEnableExtensions
= !!*(PDWORD
)Buffer
;
1977 else if (dwType
== REG_SZ
)
1978 bEnableExtensions
= (_ttol((PTSTR
)Buffer
) == 1);
1980 // else, use the default setting set globally.
1982 len
= sizeof(Buffer
);
1983 lRet
= RegQueryValueEx(hKey
,
1984 _T("CompletionChar"),
1989 if (lRet
== ERROR_SUCCESS
)
1991 /* Overwrite the default setting */
1992 if (dwType
== REG_DWORD
)
1993 AutoCompletionChar
= (TCHAR
)*(PDWORD
)Buffer
;
1994 else if (dwType
== REG_SZ
)
1995 AutoCompletionChar
= (TCHAR
)_tcstol((PTSTR
)Buffer
, NULL
, 0);
1997 // else, use the default setting set globally.
1999 /* Validity check */
2000 if (IS_COMPLETION_DISABLED(AutoCompletionChar
))
2002 /* Disable autocompletion */
2003 AutoCompletionChar
= 0x20;
2006 len
= sizeof(Buffer
);
2007 lRet
= RegQueryValueEx(hKey
,
2008 _T("PathCompletionChar"),
2013 if (lRet
== ERROR_SUCCESS
)
2015 /* Overwrite the default setting */
2016 if (dwType
== REG_DWORD
)
2017 PathCompletionChar
= (TCHAR
)*(PDWORD
)Buffer
;
2018 else if (dwType
== REG_SZ
)
2019 PathCompletionChar
= (TCHAR
)_tcstol((PTSTR
)Buffer
, NULL
, 0);
2021 // else, use the default setting set globally.
2023 /* Validity check */
2024 if (IS_COMPLETION_DISABLED(PathCompletionChar
))
2026 /* Disable autocompletion */
2027 PathCompletionChar
= 0x20;
2030 /* Adjust completion chars */
2031 if (PathCompletionChar
>= 0x20 && AutoCompletionChar
< 0x20)
2032 PathCompletionChar
= AutoCompletionChar
;
2033 else if (AutoCompletionChar
>= 0x20 && PathCompletionChar
< 0x20)
2034 AutoCompletionChar
= PathCompletionChar
;
2040 ExecuteAutoRunFile(HKEY hKeyRoot
)
2045 TCHAR AutoRun
[2048];
2047 lRet
= RegOpenKeyEx(hKeyRoot
,
2048 _T("Software\\Microsoft\\Command Processor"),
2052 if (lRet
!= ERROR_SUCCESS
)
2055 len
= sizeof(AutoRun
);
2056 lRet
= RegQueryValueEx(hKey
,
2062 if ((lRet
== ERROR_SUCCESS
) && (dwType
== REG_EXPAND_SZ
|| dwType
== REG_SZ
))
2065 ParseCommandLine(AutoRun
);
2071 /* Get the command that comes after a /C or /K switch */
2074 OUT LPTSTR commandline
,
2076 IN BOOL AlwaysStrip
)
2080 while (_istspace(*ptr
))
2083 /* Remove leading quote, find final quote */
2084 if (*ptr
== _T('"') &&
2085 (LastQuote
= _tcsrchr(++ptr
, _T('"'))) != NULL
)
2088 /* Under certain circumstances, all quotes are preserved.
2089 * CMD /? documents these conditions as follows:
2091 * 2. Exactly two quotes
2092 * 3. No "special characters" between the quotes
2093 * (CMD /? says &<>()@^| but parentheses did not
2094 * trigger this rule when I tested them.)
2095 * 4. Whitespace exists between the quotes
2096 * 5. Enclosed string is an executable filename
2098 *LastQuote
= _T('\0');
2099 for (Space
= ptr
+ 1; Space
< LastQuote
; ++Space
)
2101 if (_istspace(*Space
)) /* Rule 4 */
2103 if (!AlwaysStrip
&& /* Rule 1 */
2104 !_tcspbrk(ptr
, _T("\"&<>@^|")) && /* Rules 2, 3 */
2105 SearchForExecutable(ptr
, commandline
)) /* Rule 5 */
2107 /* All conditions met: preserve both the quotes */
2108 *LastQuote
= _T('"');
2109 _tcscpy(commandline
, ptr
- 1);
2116 /* The conditions were not met: remove both the
2117 * leading quote and the last quote */
2118 _tcscpy(commandline
, ptr
);
2119 _tcscpy(&commandline
[LastQuote
- ptr
], LastQuote
+ 1);
2123 /* No quotes; just copy */
2124 _tcscpy(commandline
, ptr
);
2129 * Set up global initializations and process parameters.
2130 * Return a pointer to the command line if present.
2135 HMODULE NtDllModule
;
2137 LPTSTR ptr
, cmdLine
;
2139 BOOL AutoRun
= TRUE
;
2140 TCHAR ModuleName
[MAX_PATH
+ 1];
2142 /* Get version information */
2145 /* Some people like to run ReactOS cmd.exe on Win98, it helps in the
2146 * build process. So don't link implicitly against ntdll.dll, load it
2147 * dynamically instead */
2148 NtDllModule
= GetModuleHandle(TEXT("ntdll.dll"));
2149 if (NtDllModule
!= NULL
)
2151 NtQueryInformationProcessPtr
= (NtQueryInformationProcessProc
)GetProcAddress(NtDllModule
, "NtQueryInformationProcess");
2152 NtReadVirtualMemoryPtr
= (NtReadVirtualMemoryProc
)GetProcAddress(NtDllModule
, "NtReadVirtualMemory");
2155 /* Load the registry settings */
2156 LoadRegistrySettings(HKEY_LOCAL_MACHINE
);
2157 LoadRegistrySettings(HKEY_CURRENT_USER
);
2159 /* Initialize our locale */
2162 /* Initialize prompt support */
2165 #ifdef FEATURE_DIRECTORY_STACK
2166 /* Initialize directory stack */
2167 InitDirectoryStack();
2170 #ifdef FEATURE_HISTORY
2171 /* Initialize history */
2175 /* Set COMSPEC environment variable */
2176 if (GetModuleFileName(NULL
, ModuleName
, ARRAYSIZE(ModuleName
)) != 0)
2178 ModuleName
[MAX_PATH
] = _T('\0');
2179 SetEnvironmentVariable (_T("COMSPEC"), ModuleName
);
2182 /* Add ctrl break handler */
2185 /* Set the default console mode */
2186 hOut
= ConStreamGetOSHandle(StdOut
);
2187 hIn
= ConStreamGetOSHandle(StdIn
);
2188 SetConsoleMode(hOut
, 0); // Reinitialize the console output mode
2189 SetConsoleMode(hOut
, ENABLE_PROCESSED_OUTPUT
| ENABLE_WRAP_AT_EOL_OUTPUT
);
2190 SetConsoleMode(hIn
, ENABLE_PROCESSED_INPUT
| ENABLE_LINE_INPUT
| ENABLE_ECHO_INPUT
);
2192 cmdLine
= GetCommandLine();
2193 TRACE ("[command args: %s]\n", debugstr_aw(cmdLine
));
2195 for (ptr
= cmdLine
; *ptr
; ++ptr
)
2197 if (*ptr
== _T('/'))
2199 option
= _totupper(ptr
[1]);
2200 if (option
== _T('?'))
2202 ConOutResPaging(TRUE
, STRING_CMD_HELP8
);
2207 else if (option
== _T('P'))
2209 if (!IsExistingFile(_T("\\autoexec.bat")))
2211 #ifdef INCLUDE_CMD_DATE
2214 #ifdef INCLUDE_CMD_TIME
2220 ParseCommandLine(_T("\\autoexec.bat"));
2224 else if (option
== _T('A'))
2226 OutputStreamMode
= AnsiText
;
2228 else if (option
== _T('C') || option
== _T('K') || option
== _T('R'))
2230 /* Remainder of command line is a command to be run */
2231 fSingleCommand
= ((option
== _T('K')) << 1) | 1;
2234 else if (option
== _T('D'))
2238 else if (option
== _T('Q'))
2240 bDisableBatchEcho
= TRUE
;
2242 else if (option
== _T('S'))
2244 bAlwaysStrip
= TRUE
;
2246 #ifdef INCLUDE_CMD_COLOR
2247 else if (!_tcsnicmp(ptr
, _T("/T:"), 3))
2249 /* Process /T (color) argument; overwrite any previous settings */
2250 wDefColor
= (WORD
)_tcstoul(&ptr
[3], &ptr
, 16);
2253 else if (option
== _T('U'))
2255 OutputStreamMode
= UTF16Text
;
2257 else if (option
== _T('V'))
2259 // FIXME: Check validity of the parameter given to V !
2260 bDelayedExpansion
= _tcsnicmp(&ptr
[2], _T(":OFF"), 4);
2262 else if (option
== _T('E'))
2264 // FIXME: Check validity of the parameter given to E !
2265 bEnableExtensions
= _tcsnicmp(&ptr
[2], _T(":OFF"), 4);
2267 else if (option
== _T('X'))
2269 /* '/X' is identical to '/E:ON' */
2270 bEnableExtensions
= TRUE
;
2272 else if (option
== _T('Y'))
2274 /* '/Y' is identical to '/E:OFF' */
2275 bEnableExtensions
= FALSE
;
2280 #ifdef INCLUDE_CMD_COLOR
2284 * If we still do not have the console colour attribute set,
2285 * retrieve the default one.
2287 ConGetDefaultAttributes(&wDefColor
);
2291 ConSetScreenColor(ConStreamGetOSHandle(StdOut
), wDefColor
, TRUE
);
2294 /* Reset the output Standard Streams translation modes and code page caches */
2295 // ConStreamSetMode(StdIn , OutputStreamMode, InputCodePage );
2296 ConStreamSetMode(StdOut
, OutputStreamMode
, OutputCodePage
);
2297 ConStreamSetMode(StdErr
, OutputStreamMode
, OutputCodePage
);
2301 /* If neither /C or /K was given, display a simple version string */
2302 ConOutChar(_T('\n'));
2303 ConOutResPrintf(STRING_REACTOS_VERSION
,
2304 _T(KERNEL_VERSION_STR
),
2305 _T(KERNEL_VERSION_BUILD_STR
));
2306 ConOutPuts(_T("(C) Copyright 1998-") _T(COPYRIGHT_YEAR
) _T(" ReactOS Team.\n"));
2311 ExecuteAutoRunFile(HKEY_LOCAL_MACHINE
);
2312 ExecuteAutoRunFile(HKEY_CURRENT_USER
);
2315 /* Returns the rest of the command line */
2320 static VOID
Cleanup(VOID
)
2322 /* Run cmdexit.bat */
2323 if (IsExistingFile(_T("cmdexit.bat")))
2325 ConErrResPuts(STRING_CMD_ERROR5
);
2326 ParseCommandLine(_T("cmdexit.bat"));
2328 else if (IsExistingFile(_T("\\cmdexit.bat")))
2330 ConErrResPuts(STRING_CMD_ERROR5
);
2331 ParseCommandLine(_T("\\cmdexit.bat"));
2334 /* Remove ctrl break handler */
2335 RemoveBreakHandler();
2337 /* Restore the default console mode */
2338 SetConsoleMode(ConStreamGetOSHandle(StdIn
),
2339 ENABLE_PROCESSED_INPUT
| ENABLE_LINE_INPUT
| ENABLE_ECHO_INPUT
);
2340 SetConsoleMode(ConStreamGetOSHandle(StdOut
),
2341 ENABLE_PROCESSED_OUTPUT
| ENABLE_WRAP_AT_EOL_OUTPUT
);
2345 #ifdef FEATURE_DIRECTORY_STACK
2346 /* Destroy directory stack */
2347 DestroyDirectoryStack();
2350 #ifdef FEATURE_HISTORY
2354 /* Free GetEnvVar's buffer */
2356 #endif /* _DEBUG_MEM */
2358 DeleteCriticalSection(&ChildProcessRunningLock
);
2364 int _tmain(int argc
, const TCHAR
*argv
[])
2368 TCHAR startPath
[MAX_PATH
];
2370 InitializeCriticalSection(&ChildProcessRunningLock
);
2371 lpOriginalEnvironment
= DuplicateEnvironment();
2373 GetCurrentDirectory(ARRAYSIZE(startPath
), startPath
);
2377 InputCodePage
= GetConsoleCP();
2378 OutputCodePage
= GetConsoleOutputCP();
2380 /* Initialize the Console Standard Streams */
2381 ConStreamInit(StdIn
, GetStdHandle(STD_INPUT_HANDLE
) , /*OutputStreamMode*/ AnsiText
, InputCodePage
);
2382 ConStreamInit(StdOut
, GetStdHandle(STD_OUTPUT_HANDLE
), OutputStreamMode
, OutputCodePage
);
2383 ConStreamInit(StdErr
, GetStdHandle(STD_ERROR_HANDLE
) , OutputStreamMode
, OutputCodePage
);
2384 /* Reset the current thread UI language */
2385 if (IsConsoleHandle(ConStreamGetOSHandle(StdOut
)) ||
2386 IsConsoleHandle(ConStreamGetOSHandle(StdErr
)))
2388 ConSetThreadUILanguage(0);
2391 CMD_ModuleHandle
= GetModuleHandle(NULL
);
2394 * Perform general initialization, parse switches on command-line.
2395 * Initialize the exit code with the errorlevel as Initialize() can set it.
2397 pCmdLine
= Initialize();
2398 nExitCode
= nErrorLevel
;
2400 if (pCmdLine
&& *pCmdLine
)
2402 TCHAR commandline
[CMDLINE_LENGTH
];
2404 /* Do the /C or /K command */
2405 GetCmdLineCommand(commandline
, &pCmdLine
[2], bAlwaysStrip
);
2406 nExitCode
= ParseCommandLine(commandline
);
2407 if (fSingleCommand
== 1)
2409 // nErrorLevel = nExitCode;
2416 /* Call prompt routine */
2417 nExitCode
= ProcessInput();
2420 /* Do the cleanup */
2422 cmd_free(lpOriginalEnvironment
);
2424 cmd_exit(nExitCode
);