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
, ULONG
, PULONG
);
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 bWaitForCommand
= FALSE
; /* When we are executing something passed on the commandline after /c or /k */
157 INT nErrorLevel
= 0; /* Errorlevel of last launched external program */
158 CRITICAL_SECTION ChildProcessRunningLock
;
159 BOOL bUnicodeOutput
= FALSE
;
160 BOOL bDisableBatchEcho
= FALSE
;
161 BOOL bEnableExtensions
= TRUE
;
162 BOOL bDelayedExpansion
= FALSE
;
163 BOOL bTitleSet
= FALSE
;
164 DWORD dwChildProcessId
= 0;
166 LPTSTR lpOriginalEnvironment
;
167 HANDLE CMD_ModuleHandle
;
169 static NtQueryInformationProcessProc NtQueryInformationProcessPtr
= NULL
;
170 static NtReadVirtualMemoryProc NtReadVirtualMemoryPtr
= NULL
;
172 #ifdef INCLUDE_CMD_COLOR
173 WORD wDefColor
= 0; /* Default color */
179 * insert commas into a number
182 ConvertULargeInteger(ULONGLONG num
, LPTSTR des
, UINT len
, BOOL bPutSeparator
)
184 TCHAR temp
[39]; /* maximum length with nNumberGroups == 1 */
191 iTarget
= nNumberGroups
;
193 bPutSeparator
= FALSE
;
197 if (iTarget
== n
&& bPutSeparator
)
199 iTarget
+= nNumberGroups
+ 1;
200 temp
[38 - n
++] = cThousandSeparator
;
202 temp
[38 - n
++] = (TCHAR
)(num
% 10) + _T('0');
208 memcpy(des
, temp
+ 39 - n
, n
* sizeof(TCHAR
));
215 * Is a process a console process?
217 static BOOL
IsConsoleProcess(HANDLE Process
)
220 PROCESS_BASIC_INFORMATION Info
;
224 if (NULL
== NtQueryInformationProcessPtr
|| NULL
== NtReadVirtualMemoryPtr
)
229 Status
= NtQueryInformationProcessPtr (
230 Process
, ProcessBasicInformation
,
231 &Info
, sizeof(PROCESS_BASIC_INFORMATION
), NULL
);
232 if (! NT_SUCCESS(Status
))
234 WARN ("NtQueryInformationProcess failed with status %08x\n", Status
);
237 Status
= NtReadVirtualMemoryPtr (
238 Process
, Info
.PebBaseAddress
, &ProcessPeb
,
239 sizeof(PEB
), &BytesRead
);
240 if (! NT_SUCCESS(Status
) || sizeof(PEB
) != BytesRead
)
242 WARN ("Couldn't read virt mem status %08x bytes read %lu\n", Status
, BytesRead
);
246 return IMAGE_SUBSYSTEM_WINDOWS_CUI
== ProcessPeb
.ImageSubsystem
;
252 #define SHELLEXECUTETEXT "ShellExecuteExW"
254 #define SHELLEXECUTETEXT "ShellExecuteExA"
257 typedef BOOL (WINAPI
*MYEX
)(LPSHELLEXECUTEINFO lpExecInfo
);
259 HANDLE
RunFile(DWORD flags
, LPTSTR filename
, LPTSTR params
,
260 LPTSTR directory
, INT show
)
262 SHELLEXECUTEINFO sei
;
267 TRACE ("RunFile(%s)\n", debugstr_aw(filename
));
268 hShell32
= LoadLibrary(_T("SHELL32.DLL"));
271 WARN ("RunFile: couldn't load SHELL32.DLL!\n");
275 hShExt
= (MYEX
)(FARPROC
)GetProcAddress(hShell32
, SHELLEXECUTETEXT
);
278 WARN ("RunFile: couldn't find ShellExecuteExA/W in SHELL32.DLL!\n");
279 FreeLibrary(hShell32
);
283 TRACE ("RunFile: ShellExecuteExA/W is at %x\n", hShExt
);
285 memset(&sei
, 0, sizeof sei
);
286 sei
.cbSize
= sizeof sei
;
288 sei
.lpFile
= filename
;
289 sei
.lpParameters
= params
;
290 sei
.lpDirectory
= directory
;
294 TRACE ("RunFile: ShellExecuteExA/W returned 0x%p\n", ret
);
296 FreeLibrary(hShell32
);
297 return ret
? sei
.hProcess
: NULL
;
303 * This command (in first) was not found in the command table
305 * Full - buffer to hold whole command line
306 * First - first word on command line
307 * Rest - rest of command line
310 Execute(LPTSTR Full
, LPTSTR First
, LPTSTR Rest
, PARSED_COMMAND
*Cmd
)
312 TCHAR szFullName
[MAX_PATH
];
313 TCHAR
*first
, *rest
, *dot
;
314 TCHAR szWindowTitle
[MAX_PATH
], szNewTitle
[MAX_PATH
*2];
315 DWORD dwExitCode
= 0;
317 TCHAR szFullCmdLine
[CMDLINE_LENGTH
];
319 TRACE ("Execute: \'%s\' \'%s\'\n", debugstr_aw(First
), debugstr_aw(Rest
));
321 /* Though it was already parsed once, we have a different set of rules
322 for parsing before we pass to CreateProcess */
323 if (First
[0] == _T('/') || (First
[0] && First
[1] == _T(':')))
325 /* Use the entire first word as the program name (no change) */
326 FirstEnd
= First
+ _tcslen(First
);
330 /* If present in the first word, spaces and ,;=/ end the program
331 * name and become the beginning of its parameters. */
332 BOOL bInside
= FALSE
;
333 for (FirstEnd
= First
; *FirstEnd
; FirstEnd
++)
335 if (!bInside
&& (_istspace(*FirstEnd
) || _tcschr(_T(",;=/"), *FirstEnd
)))
337 bInside
^= *FirstEnd
== _T('"');
341 /* Copy the new first/rest into the buffer */
343 rest
= &Full
[FirstEnd
- First
+ 1];
344 _tcscpy(rest
, FirstEnd
);
346 *FirstEnd
= _T('\0');
347 _tcscpy(first
, First
);
349 /* check for a drive change */
350 if ((_istalpha (first
[0])) && (!_tcscmp (first
+ 1, _T(":"))))
353 if (!SetCurrentDirectory(first
))
354 /* Guess they changed disc or something, handle that gracefully and get to root */
361 working
= SetCurrentDirectory(str
);
364 if (!working
) ConErrResPuts (STRING_FREE_ERROR1
);
368 /* get the PATH environment variable and parse it */
369 /* search the PATH environment variable for the binary */
371 if (!SearchForExecutable(First
, szFullName
))
373 error_bad_command(first
);
377 /* Save the original console title and build a new one */
378 GetConsoleTitle(szWindowTitle
, ARRAYSIZE(szWindowTitle
));
380 _stprintf(szNewTitle
, _T("%s - %s%s"), szWindowTitle
, First
, Rest
);
381 ConSetTitle(szNewTitle
);
383 /* check if this is a .BAT or .CMD file */
384 dot
= _tcsrchr (szFullName
, _T('.'));
385 if (dot
&& (!_tcsicmp (dot
, _T(".bat")) || !_tcsicmp (dot
, _T(".cmd"))))
387 while (*rest
== _T(' '))
389 TRACE ("[BATCH: %s %s]\n", debugstr_aw(szFullName
), debugstr_aw(rest
));
390 dwExitCode
= Batch(szFullName
, first
, rest
, Cmd
);
394 /* exec the program */
395 PROCESS_INFORMATION prci
;
398 /* build command line for CreateProcess(): FullName + " " + rest */
399 BOOL quoted
= !!_tcschr(First
, ' ');
400 _tcscpy(szFullCmdLine
, quoted
? _T("\"") : _T(""));
401 _tcsncat(szFullCmdLine
, First
, CMDLINE_LENGTH
- _tcslen(szFullCmdLine
) - 1);
402 _tcsncat(szFullCmdLine
, quoted
? _T("\"") : _T(""), CMDLINE_LENGTH
- _tcslen(szFullCmdLine
) - 1);
406 _tcsncat(szFullCmdLine
, _T(" "), CMDLINE_LENGTH
- _tcslen(szFullCmdLine
) - 1);
407 _tcsncat(szFullCmdLine
, rest
, CMDLINE_LENGTH
- _tcslen(szFullCmdLine
) - 1);
410 TRACE ("[EXEC: %s]\n", debugstr_aw(szFullCmdLine
));
412 /* fill startup info */
413 memset (&stui
, 0, sizeof (STARTUPINFO
));
414 stui
.cb
= sizeof (STARTUPINFO
);
415 stui
.dwFlags
= STARTF_USESHOWWINDOW
;
416 stui
.wShowWindow
= SW_SHOWDEFAULT
;
418 /* Set the console to standard mode */
419 SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE
),
420 ENABLE_PROCESSED_INPUT
| ENABLE_LINE_INPUT
| ENABLE_ECHO_INPUT
);
422 if (CreateProcess(szFullName
,
427 0, /* CREATE_NEW_PROCESS_GROUP */
433 CloseHandle(prci
.hThread
);
437 // See if we can run this with ShellExecute() ie myfile.xls
438 prci
.hProcess
= RunFile(SEE_MASK_NOCLOSEPROCESS
| SEE_MASK_NO_CONSOLE
,
445 if (prci
.hProcess
!= NULL
)
447 if (bc
!= NULL
|| bWaitForCommand
|| IsConsoleProcess(prci
.hProcess
))
449 /* when processing a batch file or starting console processes: execute synchronously */
450 EnterCriticalSection(&ChildProcessRunningLock
);
451 dwChildProcessId
= prci
.dwProcessId
;
453 WaitForSingleObject(prci
.hProcess
, INFINITE
);
455 LeaveCriticalSection(&ChildProcessRunningLock
);
457 GetExitCodeProcess(prci
.hProcess
, &dwExitCode
);
458 nErrorLevel
= (INT
)dwExitCode
;
460 CloseHandle(prci
.hProcess
);
464 TRACE ("[ShellExecute failed!: %s]\n", debugstr_aw(Full
));
465 error_bad_command(first
);
469 /* Restore our default console mode */
470 SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE
),
471 ENABLE_PROCESSED_INPUT
| ENABLE_LINE_INPUT
| ENABLE_ECHO_INPUT
);
472 SetConsoleMode(GetStdHandle(STD_OUTPUT_HANDLE
),
473 ENABLE_PROCESSED_OUTPUT
| ENABLE_WRAP_AT_EOL_OUTPUT
);
476 /* Get code page if it has been changed */
477 InputCodePage
= GetConsoleCP();
478 OutputCodePage
= GetConsoleOutputCP();
480 /* Restore the original console title */
482 ConSetTitle(szWindowTitle
);
489 * look through the internal commands and determine whether or not this
490 * command is one of them. If it is, call the command. If not, call
491 * execute to run it as an external program.
493 * first - first word on command line
494 * rest - rest of command line
497 DoCommand(LPTSTR first
, LPTSTR rest
, PARSED_COMMAND
*Cmd
)
501 LPTSTR param
; /* pointer to command's parameters */
504 BOOL nointernal
= FALSE
;
507 TRACE ("DoCommand: (\'%s\' \'%s\')\n", debugstr_aw(first
), debugstr_aw(rest
));
509 /* full command line */
510 com
= cmd_alloc((_tcslen(first
) + _tcslen(rest
) + 2) * sizeof(TCHAR
));
513 error_out_of_memory();
517 /* If present in the first word, these characters end the name of an
518 * internal command and become the beginning of its parameters. */
519 cp
= first
+ _tcscspn(first
, _T("\t +,/;=[]"));
521 for (cl
= 0; cl
< (cp
- first
); cl
++)
523 /* These characters do it too, but if one of them is present,
524 * then we check to see if the word is a file name and skip
525 * checking for internal commands if so.
526 * This allows running programs with names like "echo.exe" */
527 if (_tcschr(_T(".:\\"), first
[cl
]))
531 nointernal
= IsExistingFile(first
);
537 /* Scan internal command table */
538 for (cmdptr
= cmds
; !nointernal
&& cmdptr
->name
; cmdptr
++)
540 if (!_tcsnicmp(first
, cmdptr
->name
, cl
) && cmdptr
->name
[cl
] == _T('\0'))
546 /* Skip over whitespace to rest of line, exclude 'echo' command */
547 if (_tcsicmp(cmdptr
->name
, _T("echo")) != 0)
548 while (_istspace(*param
))
550 ret
= cmdptr
->func(param
);
556 ret
= Execute(com
, first
, rest
, Cmd
);
563 * process the command line and execute the appropriate functions
564 * full input/output redirection and piping are supported
566 INT
ParseCommandLine(LPTSTR cmd
)
569 PARSED_COMMAND
*Cmd
= ParseCommand(cmd
);
572 Ret
= ExecuteCommand(Cmd
);
578 /* Execute a command without waiting for it to finish. If it's an internal
579 * command or batch file, we must create a new cmd.exe process to handle it.
580 * TODO: For now, this just always creates a cmd.exe process.
581 * This works, but is inefficient for running external programs,
582 * which could just be run directly. */
584 ExecuteAsync(PARSED_COMMAND
*Cmd
)
586 TCHAR CmdPath
[MAX_PATH
];
587 TCHAR CmdParams
[CMDLINE_LENGTH
], *ParamsEnd
;
589 PROCESS_INFORMATION prci
;
591 /* Get the path to cmd.exe */
592 GetModuleFileName(NULL
, CmdPath
, ARRAYSIZE(CmdPath
));
594 /* Build the parameter string to pass to cmd.exe */
595 ParamsEnd
= _stpcpy(CmdParams
, _T("/S/D/C\""));
596 ParamsEnd
= Unparse(Cmd
, ParamsEnd
, &CmdParams
[CMDLINE_LENGTH
- 2]);
599 error_out_of_memory();
602 _tcscpy(ParamsEnd
, _T("\""));
604 memset(&stui
, 0, sizeof stui
);
605 stui
.cb
= sizeof(STARTUPINFO
);
606 if (!CreateProcess(CmdPath
, CmdParams
, NULL
, NULL
, TRUE
, 0,
607 NULL
, NULL
, &stui
, &prci
))
609 ErrorMessage(GetLastError(), NULL
);
613 CloseHandle(prci
.hThread
);
614 return prci
.hProcess
;
618 ExecutePipeline(PARSED_COMMAND
*Cmd
)
620 #ifdef FEATURE_REDIRECTION
621 HANDLE hInput
= NULL
;
622 HANDLE hOldConIn
= GetStdHandle(STD_INPUT_HANDLE
);
623 HANDLE hOldConOut
= GetStdHandle(STD_OUTPUT_HANDLE
);
624 HANDLE hProcess
[MAXIMUM_WAIT_OBJECTS
];
628 /* Do all but the last pipe command */
631 HANDLE hPipeRead
, hPipeWrite
;
632 if (nProcesses
> (MAXIMUM_WAIT_OBJECTS
- 2))
634 error_too_many_parameters(_T("|"));
638 /* Create the pipe that this process will write into.
639 * Make the handles non-inheritable initially, because this
640 * process shouldn't inherit the reading handle. */
641 if (!CreatePipe(&hPipeRead
, &hPipeWrite
, NULL
, 0))
647 /* The writing side of the pipe is STDOUT for this process */
648 SetHandleInformation(hPipeWrite
, HANDLE_FLAG_INHERIT
, HANDLE_FLAG_INHERIT
);
649 SetStdHandle(STD_OUTPUT_HANDLE
, hPipeWrite
);
651 /* Execute it (error check is done later for easier cleanup) */
652 hProcess
[nProcesses
] = ExecuteAsync(Cmd
->Subcommands
);
653 CloseHandle(hPipeWrite
);
657 /* The reading side of the pipe will be STDIN for the next process */
658 SetHandleInformation(hPipeRead
, HANDLE_FLAG_INHERIT
, HANDLE_FLAG_INHERIT
);
659 SetStdHandle(STD_INPUT_HANDLE
, hPipeRead
);
662 if (!hProcess
[nProcesses
])
666 Cmd
= Cmd
->Subcommands
->Next
;
667 } while (Cmd
->Type
== C_PIPE
);
669 /* The last process uses the original STDOUT */
670 SetStdHandle(STD_OUTPUT_HANDLE
, hOldConOut
);
671 hProcess
[nProcesses
] = ExecuteAsync(Cmd
);
672 if (!hProcess
[nProcesses
])
676 SetStdHandle(STD_INPUT_HANDLE
, hOldConIn
);
678 /* Wait for all processes to complete */
679 EnterCriticalSection(&ChildProcessRunningLock
);
680 WaitForMultipleObjects(nProcesses
, hProcess
, TRUE
, INFINITE
);
681 LeaveCriticalSection(&ChildProcessRunningLock
);
683 /* Use the exit code of the last process in the pipeline */
684 GetExitCodeProcess(hProcess
[nProcesses
- 1], &dwExitCode
);
685 nErrorLevel
= (INT
)dwExitCode
;
687 while (--nProcesses
>= 0)
688 CloseHandle(hProcess
[nProcesses
]);
694 while (--nProcesses
>= 0)
696 TerminateProcess(hProcess
[nProcesses
], 0);
697 CloseHandle(hProcess
[nProcesses
]);
699 SetStdHandle(STD_INPUT_HANDLE
, hOldConIn
);
700 SetStdHandle(STD_OUTPUT_HANDLE
, hOldConOut
);
705 ExecuteCommand(PARSED_COMMAND
*Cmd
)
711 if (!PerformRedirection(Cmd
->Redirections
))
718 First
= DoDelayedExpansion(Cmd
->Command
.First
);
721 Rest
= DoDelayedExpansion(Cmd
->Command
.Rest
);
724 Ret
= DoCommand(First
, Rest
, Cmd
);
733 for (Sub
= Cmd
->Subcommands
; Sub
; Sub
= Sub
->Next
)
734 Ret
= ExecuteCommand(Sub
);
737 Sub
= Cmd
->Subcommands
;
738 Ret
= ExecuteCommand(Sub
);
742 Ret
= ExecuteCommand(Sub
->Next
);
746 Sub
= Cmd
->Subcommands
;
747 Ret
= ExecuteCommand(Sub
);
749 Ret
= ExecuteCommand(Sub
->Next
);
752 ExecutePipeline(Cmd
);
755 Ret
= ExecuteIf(Cmd
);
758 Ret
= ExecuteFor(Cmd
);
762 UndoRedirection(Cmd
->Redirections
, NULL
);
767 GetEnvVar(LPCTSTR varName
)
769 static LPTSTR ret
= NULL
;
774 size
= GetEnvironmentVariable(varName
, NULL
, 0);
777 ret
= cmd_alloc(size
* sizeof(TCHAR
));
779 GetEnvironmentVariable(varName
, ret
, size
+ 1);
785 GetEnvVarOrSpecial(LPCTSTR varName
)
787 static TCHAR ret
[MAX_PATH
];
789 LPTSTR var
= GetEnvVar(varName
);
793 /* env var doesn't exist, look for a "special" one */
795 if (_tcsicmp(varName
,_T("cd")) ==0)
797 GetCurrentDirectory(MAX_PATH
, ret
);
801 else if (_tcsicmp(varName
,_T("time")) ==0)
803 return GetTimeString();
806 else if (_tcsicmp(varName
,_T("date")) ==0)
808 return GetDateString();
812 else if (_tcsicmp(varName
,_T("random")) ==0)
814 /* Get random number */
815 _itot(rand(),ret
,10);
820 else if (_tcsicmp(varName
,_T("cmdcmdline")) ==0)
822 return GetCommandLine();
825 /* %CMDEXTVERSION% */
826 else if (_tcsicmp(varName
,_T("cmdextversion")) ==0)
828 /* Set version number to 2 */
834 else if (_tcsicmp(varName
,_T("errorlevel")) ==0)
836 _itot(nErrorLevel
,ret
,10);
843 /* Handle the %~var syntax */
845 GetEnhancedVar(TCHAR
**pFormat
, LPTSTR (*GetVar
)(TCHAR
, BOOL
*))
847 static const TCHAR ModifierTable
[] = _T("dpnxfsatz");
849 M_DRIVE
= 1, /* D: drive letter */
850 M_PATH
= 2, /* P: path */
851 M_NAME
= 4, /* N: filename */
852 M_EXT
= 8, /* X: extension */
853 M_FULL
= 16, /* F: full path (drive+path+name+ext) */
854 M_SHORT
= 32, /* S: full path (drive+path+name+ext), use short names */
855 M_ATTR
= 64, /* A: attributes */
856 M_TIME
= 128, /* T: modification time */
857 M_SIZE
= 256, /* Z: file size */
860 TCHAR
*Format
, *FormatEnd
;
861 TCHAR
*PathVarName
= NULL
;
864 BOOL VariableIsParam0
;
865 TCHAR FullPath
[MAX_PATH
];
866 TCHAR FixedPath
[MAX_PATH
], *Filename
, *Extension
;
868 WIN32_FIND_DATA w32fd
;
871 static TCHAR Result
[CMDLINE_LENGTH
];
873 /* There is ambiguity between modifier characters and FOR variables;
874 * the rule that cmd uses is to pick the longest possible match.
875 * For example, if there is a %n variable, then out of %~anxnd,
876 * %~anxn will be substituted rather than just %~an. */
878 /* First, go through as many modifier characters as possible */
879 FormatEnd
= Format
= *pFormat
;
880 while (*FormatEnd
&& _tcschr(ModifierTable
, _totlower(*FormatEnd
)))
883 if (*FormatEnd
== _T('$'))
886 PathVarName
= FormatEnd
+ 1;
887 FormatEnd
= _tcschr(PathVarName
, _T(':'));
891 /* Must be immediately followed by the variable */
892 Variable
= GetVar(*++FormatEnd
, &VariableIsParam0
);
898 /* Backtrack if necessary to get a variable name match */
899 while (!(Variable
= GetVar(*FormatEnd
, &VariableIsParam0
)))
901 if (FormatEnd
== Format
)
907 for (; Format
< FormatEnd
&& *Format
!= _T('$'); Format
++)
908 Modifiers
|= 1 << (_tcschr(ModifierTable
, _totlower(*Format
)) - ModifierTable
);
910 *pFormat
= FormatEnd
+ 1;
912 /* Exclude the leading and trailing quotes */
913 VarEnd
= &Variable
[_tcslen(Variable
)];
914 if (*Variable
== _T('"'))
917 if (VarEnd
> Variable
&& VarEnd
[-1] == _T('"'))
921 if ((char *)VarEnd
- (char *)Variable
>= sizeof Result
)
923 memcpy(Result
, Variable
, (char *)VarEnd
- (char *)Variable
);
924 Result
[VarEnd
- Variable
] = _T('\0');
928 /* $PATH: syntax - search the directories listed in the
929 * specified environment variable for the file */
931 FormatEnd
[-1] = _T('\0');
932 PathVar
= GetEnvVar(PathVarName
);
933 FormatEnd
[-1] = _T(':');
935 !SearchPath(PathVar
, Result
, NULL
, MAX_PATH
, FullPath
, NULL
))
940 else if (Modifiers
== 0)
942 /* For plain %~var with no modifiers, just return the variable without quotes */
945 else if (VariableIsParam0
)
947 /* Special case: If the variable is %0 and modifier characters are present,
948 * use the batch file's path (which includes the .bat/.cmd extension)
949 * rather than the actual %0 variable (which might not). */
950 _tcscpy(FullPath
, bc
->BatchFilePath
);
954 /* Convert the variable, now without quotes, to a full path */
955 if (!GetFullPathName(Result
, MAX_PATH
, FullPath
, NULL
))
959 /* Next step is to change the path to fix letter case (e.g.
960 * C:\ReAcToS -> C:\ReactOS) and, if requested with the S modifier,
961 * replace long filenames with short. */
966 /* Copy drive letter */
970 /* Loop over each \-separated component in the path */
972 TCHAR
*Next
= _tcschr(In
, _T('\\'));
975 /* Use FindFirstFile to get the correct name */
976 if (Out
+ _tcslen(In
) + 1 >= &FixedPath
[MAX_PATH
])
979 hFind
= FindFirstFile(FixedPath
, &w32fd
);
980 /* If it doesn't exist, just leave the name as it was given */
981 if (hFind
!= INVALID_HANDLE_VALUE
)
983 LPTSTR FixedComponent
= w32fd
.cFileName
;
984 if (*w32fd
.cAlternateFileName
&&
985 ((Modifiers
& M_SHORT
) || !_tcsicmp(In
, w32fd
.cAlternateFileName
)))
987 FixedComponent
= w32fd
.cAlternateFileName
;
991 if (Out
+ _tcslen(FixedComponent
) + 1 >= &FixedPath
[MAX_PATH
])
993 _tcscpy(Out
, FixedComponent
);
1000 } while (In
!= NULL
);
1003 /* Build the result string. Start with attributes, modification time, and
1004 * file size. If the file didn't exist, these fields will all be empty. */
1006 if (hFind
!= INVALID_HANDLE_VALUE
)
1008 if (Modifiers
& M_ATTR
)
1010 static const struct {
1013 } *Attrib
, Table
[] = {
1014 { _T('d'), FILE_ATTRIBUTE_DIRECTORY
},
1015 { _T('r'), FILE_ATTRIBUTE_READONLY
},
1016 { _T('a'), FILE_ATTRIBUTE_ARCHIVE
},
1017 { _T('h'), FILE_ATTRIBUTE_HIDDEN
},
1018 { _T('s'), FILE_ATTRIBUTE_SYSTEM
},
1019 { _T('c'), FILE_ATTRIBUTE_COMPRESSED
},
1020 { _T('o'), FILE_ATTRIBUTE_OFFLINE
},
1021 { _T('t'), FILE_ATTRIBUTE_TEMPORARY
},
1022 { _T('l'), FILE_ATTRIBUTE_REPARSE_POINT
},
1024 for (Attrib
= Table
; Attrib
!= &Table
[9]; Attrib
++)
1026 *Out
++ = w32fd
.dwFileAttributes
& Attrib
->Value
1032 if (Modifiers
& M_TIME
)
1036 FileTimeToLocalFileTime(&w32fd
.ftLastWriteTime
, &ft
);
1037 FileTimeToSystemTime(&ft
, &st
);
1039 Out
+= FormatDate(Out
, &st
, TRUE
);
1041 Out
+= FormatTime(Out
, &st
);
1044 if (Modifiers
& M_SIZE
)
1046 ULARGE_INTEGER Size
;
1047 Size
.LowPart
= w32fd
.nFileSizeLow
;
1048 Size
.HighPart
= w32fd
.nFileSizeHigh
;
1049 Out
+= _stprintf(Out
, _T("%I64u "), Size
.QuadPart
);
1053 /* When using the path-searching syntax or the S modifier,
1054 * at least part of the file path is always included.
1055 * If none of the DPNX modifiers are present, include the full path */
1056 if (PathVarName
|| (Modifiers
& M_SHORT
))
1057 if ((Modifiers
& (M_DRIVE
| M_PATH
| M_NAME
| M_EXT
)) == 0)
1058 Modifiers
|= M_FULL
;
1060 /* Now add the requested parts of the name.
1061 * With the F modifier, add all parts to form the full path. */
1062 Extension
= _tcsrchr(Filename
, _T('.'));
1063 if (Modifiers
& (M_DRIVE
| M_FULL
))
1065 *Out
++ = FixedPath
[0];
1066 *Out
++ = FixedPath
[1];
1068 if (Modifiers
& (M_PATH
| M_FULL
))
1070 memcpy(Out
, &FixedPath
[2], (char *)Filename
- (char *)&FixedPath
[2]);
1071 Out
+= Filename
- &FixedPath
[2];
1073 if (Modifiers
& (M_NAME
| M_FULL
))
1075 while (*Filename
&& Filename
!= Extension
)
1076 *Out
++ = *Filename
++;
1078 if (Modifiers
& (M_EXT
| M_FULL
))
1081 Out
= _stpcpy(Out
, Extension
);
1084 /* Trim trailing space which otherwise would appear as a
1085 * result of using the A/T/Z modifiers but no others. */
1086 while (Out
!= &Result
[0] && Out
[-1] == _T(' '))
1094 GetBatchVar(TCHAR
*varName
, UINT
*varNameLen
)
1105 varNameEnd
= varName
+ 1;
1106 ret
= GetEnhancedVar(&varNameEnd
, FindArg
);
1109 error_syntax(varName
);
1112 *varNameLen
= varNameEnd
- varName
;
1124 return FindArg(*varName
, &dummy
);
1128 // Copy over the raw params(not including the batch file name
1130 return bc
->raw_params
;
1139 SubstituteVars(TCHAR
*Src
, TCHAR
*Dest
, TCHAR Delim
)
1141 #define APPEND(From, Length) { \
1142 if (Dest + (Length) > DestEnd) \
1144 memcpy(Dest, From, (Length) * sizeof(TCHAR)); \
1146 #define APPEND1(Char) { \
1147 if (Dest >= DestEnd) \
1151 TCHAR
*DestEnd
= Dest
+ CMDLINE_LENGTH
- 1;
1165 if (bc
&& Delim
== _T('%'))
1168 Var
= GetBatchVar(Src
, &NameLen
);
1171 VarLength
= _tcslen(Var
);
1172 APPEND(Var
, VarLength
)
1178 /* Find the end of the variable name. A colon (:) will usually
1179 * end the name and begin the optional modifier, but not if it
1180 * is immediately followed by the delimiter (%VAR:%). */
1182 while (*Src
!= Delim
&& !(*Src
== _T(':') && Src
[1] != Delim
))
1191 Var
= GetEnvVarOrSpecial(SubstStart
);
1195 /* In a batch file, %NONEXISTENT% "expands" to an empty string */
1200 VarLength
= _tcslen(Var
);
1202 if (EndChr
== Delim
)
1204 /* %VAR% - use as-is */
1205 APPEND(Var
, VarLength
)
1207 else if (*Src
== _T('~'))
1209 /* %VAR:~[start][,length]% - substring
1210 * Negative values are offsets from the end */
1211 int Start
= _tcstol(Src
+ 1, &Src
, 0);
1212 int End
= VarLength
;
1215 Start
= max(Start
, 0);
1216 Start
= min(Start
, VarLength
);
1217 if (*Src
== _T(','))
1219 End
= _tcstol(Src
+ 1, &Src
, 0);
1220 End
+= (End
< 0) ? VarLength
: Start
;
1221 End
= max(End
, Start
);
1222 End
= min(End
, VarLength
);
1224 if (*Src
++ != Delim
)
1226 APPEND(&Var
[Start
], End
- Start
);
1230 /* %VAR:old=new% - replace all occurrences of old with new
1231 * %VAR:*old=new% - replace first occurrence only,
1232 * and remove everything before it */
1234 DWORD OldLength
, NewLength
;
1236 int LastMatch
= 0, i
= 0;
1238 if (*Src
== _T('*'))
1244 /* the string to replace may contain the delimiter */
1245 Src
= _tcschr(Old
= Src
, _T('='));
1248 OldLength
= Src
++ - Old
;
1252 Src
= _tcschr(New
= Src
, Delim
);
1255 NewLength
= Src
++ - New
;
1257 while (i
< VarLength
)
1259 if (_tcsnicmp(&Var
[i
], Old
, OldLength
) == 0)
1262 APPEND(&Var
[LastMatch
], i
- LastMatch
)
1263 APPEND(New
, NewLength
)
1272 APPEND(&Var
[LastMatch
], VarLength
- LastMatch
)
1284 ConOutResPrintf(STRING_ALIAS_ERROR
);
1291 /* Search the list of FOR contexts for a variable */
1292 static LPTSTR
FindForVar(TCHAR Var
, BOOL
*IsParam0
)
1296 for (Ctx
= fc
; Ctx
!= NULL
; Ctx
= Ctx
->prev
)
1298 if ((UINT
)(Var
- Ctx
->firstvar
) < Ctx
->varcount
)
1299 return Ctx
->values
[Var
- Ctx
->firstvar
];
1305 SubstituteForVars(TCHAR
*Src
, TCHAR
*Dest
)
1307 TCHAR
*DestEnd
= &Dest
[CMDLINE_LENGTH
- 1];
1310 if (Src
[0] == _T('%'))
1313 LPTSTR End
= &Src
[2];
1314 LPTSTR Value
= NULL
;
1316 if (Src
[1] == _T('~'))
1317 Value
= GetEnhancedVar(&End
, FindForVar
);
1320 Value
= FindForVar(Src
[1], &Dummy
);
1324 if (Dest
+ _tcslen(Value
) > DestEnd
)
1326 Dest
= _stpcpy(Dest
, Value
);
1331 /* Not a variable; just copy the character */
1332 if (Dest
>= DestEnd
)
1341 DoDelayedExpansion(LPTSTR Line
)
1343 TCHAR Buf1
[CMDLINE_LENGTH
];
1344 TCHAR Buf2
[CMDLINE_LENGTH
];
1346 /* First, substitute FOR variables */
1347 if (!SubstituteForVars(Line
, Buf1
))
1350 if (!bDelayedExpansion
|| !_tcschr(Buf1
, _T('!')))
1351 return cmd_dup(Buf1
);
1353 /* FIXME: Delayed substitutions actually aren't quite the same as
1354 * immediate substitutions. In particular, it's possible to escape
1355 * the exclamation point using ^. */
1356 if (!SubstituteVars(Buf1
, Buf2
, _T('!')))
1358 return cmd_dup(Buf2
);
1363 * do the prompt/input/process loop
1368 ReadLine(TCHAR
*commandline
, BOOL bMore
)
1370 TCHAR readline
[CMDLINE_LENGTH
];
1373 /* if no batch input then... */
1378 ConOutResPrintf(STRING_MORE
);
1382 /* JPP 19980807 - if echo off, don't print prompt */
1386 ConOutChar(_T('\n'));
1391 if (!ReadCommand(readline
, CMDLINE_LENGTH
- 1))
1397 if (CheckCtrlBreak(BREAK_INPUT
))
1399 ConOutChar(_T('\n'));
1406 ip
= ReadBatchLine();
1411 return SubstituteVars(ip
, commandline
, _T('%'));
1417 PARSED_COMMAND
*Cmd
;
1419 while (!bCanExit
|| !bExit
)
1421 Cmd
= ParseCommand(NULL
);
1425 ExecuteCommand(Cmd
);
1432 * control-break handler.
1434 BOOL WINAPI
BreakHandler(DWORD dwCtrlType
)
1438 static BOOL SelfGenerated
= FALSE
;
1440 if ((dwCtrlType
!= CTRL_C_EVENT
) &&
1441 (dwCtrlType
!= CTRL_BREAK_EVENT
))
1449 SelfGenerated
= FALSE
;
1454 if (!TryEnterCriticalSection(&ChildProcessRunningLock
))
1456 SelfGenerated
= TRUE
;
1457 GenerateConsoleCtrlEvent (dwCtrlType
, 0);
1462 LeaveCriticalSection(&ChildProcessRunningLock
);
1465 rec
.EventType
= KEY_EVENT
;
1466 rec
.Event
.KeyEvent
.bKeyDown
= TRUE
;
1467 rec
.Event
.KeyEvent
.wRepeatCount
= 1;
1468 rec
.Event
.KeyEvent
.wVirtualKeyCode
= _T('C');
1469 rec
.Event
.KeyEvent
.wVirtualScanCode
= _T('C') - 35;
1470 rec
.Event
.KeyEvent
.uChar
.AsciiChar
= _T('C');
1471 rec
.Event
.KeyEvent
.uChar
.UnicodeChar
= _T('C');
1472 rec
.Event
.KeyEvent
.dwControlKeyState
= RIGHT_CTRL_PRESSED
;
1474 WriteConsoleInput(hIn
,
1480 /* FIXME: Handle batch files */
1482 //ConOutPrintf(_T("^C"));
1488 VOID
AddBreakHandler(VOID
)
1490 SetConsoleCtrlHandler(BreakHandler
, TRUE
);
1494 VOID
RemoveBreakHandler(VOID
)
1496 SetConsoleCtrlHandler(BreakHandler
, FALSE
);
1501 * show commands and options that are available.
1508 /* print command list */
1509 ConOutResPuts(STRING_CMD_HELP1
);
1512 /* print feature list */
1513 ConOutResPuts(STRING_CMD_HELP2
);
1515 #ifdef FEATURE_ALIASES
1516 ConOutResPuts(STRING_CMD_HELP3
);
1518 #ifdef FEATURE_HISTORY
1519 ConOutResPuts(STRING_CMD_HELP4
);
1521 #ifdef FEATURE_UNIX_FILENAME_COMPLETION
1522 ConOutResPuts(STRING_CMD_HELP5
);
1524 #ifdef FEATURE_DIRECTORY_STACK
1525 ConOutResPuts(STRING_CMD_HELP6
);
1527 #ifdef FEATURE_REDIRECTION
1528 ConOutResPuts(STRING_CMD_HELP7
);
1530 ConOutChar(_T('\n'));
1536 LoadRegistrySettings(HKEY hKeyRoot
)
1541 * Buffer big enough to hold the string L"4294967295",
1542 * corresponding to the literal 0xFFFFFFFF (MAX_ULONG) in decimal.
1547 lRet
= RegOpenKeyEx(hKeyRoot
,
1548 _T("Software\\Microsoft\\Command Processor"),
1552 if (lRet
!= ERROR_SUCCESS
)
1555 #ifdef INCLUDE_CMD_COLOR
1556 len
= sizeof(Buffer
);
1557 lRet
= RegQueryValueEx(hKey
,
1563 if (lRet
== ERROR_SUCCESS
)
1565 /* Overwrite the default attributes */
1566 if (dwType
== REG_DWORD
)
1567 wDefColor
= (WORD
)*(PDWORD
)Buffer
;
1568 else if (dwType
== REG_SZ
)
1569 wDefColor
= (WORD
)_tcstol((PTSTR
)Buffer
, NULL
, 0);
1571 // else, use the default attributes retrieved before.
1575 len
= sizeof(Buffer
);
1576 lRet
= RegQueryValueEx(hKey
,
1577 _T("DisableUNCCheck"),
1582 if (lRet
== ERROR_SUCCESS
)
1584 /* Overwrite the default setting */
1585 if (dwType
== REG_DWORD
)
1586 bDisableUNCCheck
= !!*(PDWORD
)Buffer
;
1587 else if (dwType
== REG_SZ
)
1588 bDisableUNCCheck
= (_ttol((PTSTR
)Buffer
) == 1);
1590 // else, use the default setting set globally.
1593 len
= sizeof(Buffer
);
1594 lRet
= RegQueryValueEx(hKey
,
1595 _T("DelayedExpansion"),
1600 if (lRet
== ERROR_SUCCESS
)
1602 /* Overwrite the default setting */
1603 if (dwType
== REG_DWORD
)
1604 bDelayedExpansion
= !!*(PDWORD
)Buffer
;
1605 else if (dwType
== REG_SZ
)
1606 bDelayedExpansion
= (_ttol((PTSTR
)Buffer
) == 1);
1608 // else, use the default setting set globally.
1610 len
= sizeof(Buffer
);
1611 lRet
= RegQueryValueEx(hKey
,
1612 _T("EnableExtensions"),
1617 if (lRet
== ERROR_SUCCESS
)
1619 /* Overwrite the default setting */
1620 if (dwType
== REG_DWORD
)
1621 bEnableExtensions
= !!*(PDWORD
)Buffer
;
1622 else if (dwType
== REG_SZ
)
1623 bEnableExtensions
= (_ttol((PTSTR
)Buffer
) == 1);
1625 // else, use the default setting set globally.
1627 len
= sizeof(Buffer
);
1628 lRet
= RegQueryValueEx(hKey
,
1629 _T("CompletionChar"),
1634 if (lRet
== ERROR_SUCCESS
)
1636 /* Overwrite the default setting */
1637 if (dwType
== REG_DWORD
)
1638 AutoCompletionChar
= (TCHAR
)*(PDWORD
)Buffer
;
1639 else if (dwType
== REG_SZ
)
1640 AutoCompletionChar
= (TCHAR
)_tcstol((PTSTR
)Buffer
, NULL
, 0);
1642 // else, use the default setting set globally.
1644 /* Validity check */
1645 if (IS_COMPLETION_DISABLED(AutoCompletionChar
))
1647 /* Disable autocompletion */
1648 AutoCompletionChar
= 0x20;
1651 len
= sizeof(Buffer
);
1652 lRet
= RegQueryValueEx(hKey
,
1653 _T("PathCompletionChar"),
1658 if (lRet
== ERROR_SUCCESS
)
1660 /* Overwrite the default setting */
1661 if (dwType
== REG_DWORD
)
1662 PathCompletionChar
= (TCHAR
)*(PDWORD
)Buffer
;
1663 else if (dwType
== REG_SZ
)
1664 PathCompletionChar
= (TCHAR
)_tcstol((PTSTR
)Buffer
, NULL
, 0);
1666 // else, use the default setting set globally.
1668 /* Validity check */
1669 if (IS_COMPLETION_DISABLED(PathCompletionChar
))
1671 /* Disable autocompletion */
1672 PathCompletionChar
= 0x20;
1675 /* Adjust completion chars */
1676 if (PathCompletionChar
>= 0x20 && AutoCompletionChar
< 0x20)
1677 PathCompletionChar
= AutoCompletionChar
;
1678 else if (AutoCompletionChar
>= 0x20 && PathCompletionChar
< 0x20)
1679 AutoCompletionChar
= PathCompletionChar
;
1685 ExecuteAutoRunFile(HKEY hKeyRoot
)
1687 TCHAR autorun
[2048];
1688 DWORD len
= sizeof autorun
;
1691 if (RegOpenKeyEx(hKeyRoot
,
1692 _T("SOFTWARE\\Microsoft\\Command Processor"),
1695 &hkey
) == ERROR_SUCCESS
)
1697 if (RegQueryValueEx(hkey
,
1702 &len
) == ERROR_SUCCESS
)
1705 ParseCommandLine(autorun
);
1711 /* Get the command that comes after a /C or /K switch */
1713 GetCmdLineCommand(TCHAR
*commandline
, TCHAR
*ptr
, BOOL AlwaysStrip
)
1717 while (_istspace(*ptr
))
1720 /* Remove leading quote, find final quote */
1721 if (*ptr
== _T('"') &&
1722 (LastQuote
= _tcsrchr(++ptr
, _T('"'))) != NULL
)
1725 /* Under certain circumstances, all quotes are preserved.
1726 * CMD /? documents these conditions as follows:
1728 * 2. Exactly two quotes
1729 * 3. No "special characters" between the quotes
1730 * (CMD /? says &<>()@^| but parentheses did not
1731 * trigger this rule when I tested them.)
1732 * 4. Whitespace exists between the quotes
1733 * 5. Enclosed string is an executable filename
1735 *LastQuote
= _T('\0');
1736 for (Space
= ptr
+ 1; Space
< LastQuote
; Space
++)
1738 if (_istspace(*Space
)) /* Rule 4 */
1740 if (!AlwaysStrip
&& /* Rule 1 */
1741 !_tcspbrk(ptr
, _T("\"&<>@^|")) && /* Rules 2, 3 */
1742 SearchForExecutable(ptr
, commandline
)) /* Rule 5 */
1744 /* All conditions met: preserve both the quotes */
1745 *LastQuote
= _T('"');
1746 _tcscpy(commandline
, ptr
- 1);
1753 /* The conditions were not met: remove both the
1754 * leading quote and the last quote */
1755 _tcscpy(commandline
, ptr
);
1756 _tcscpy(&commandline
[LastQuote
- ptr
], LastQuote
+ 1);
1760 /* No quotes; just copy */
1761 _tcscpy(commandline
, ptr
);
1765 #ifdef INCLUDE_CMD_COLOR
1767 BOOL
ConGetDefaultAttributes(PWORD pwDefAttr
)
1771 CONSOLE_SCREEN_BUFFER_INFO csbi
;
1773 /* Do not modify *pwDefAttr if we fail, in which case use default attributes */
1775 hConsole
= CreateFile(_T("CONOUT$"), GENERIC_READ
|GENERIC_WRITE
,
1776 FILE_SHARE_READ
|FILE_SHARE_WRITE
, NULL
,
1777 OPEN_EXISTING
, 0, NULL
);
1778 if (hConsole
== INVALID_HANDLE_VALUE
)
1779 return FALSE
; // No default console
1781 Success
= GetConsoleScreenBufferInfo(hConsole
, &csbi
);
1783 *pwDefAttr
= csbi
.wAttributes
;
1785 CloseHandle(hConsole
);
1793 * Set up global initializations and process parameters
1798 HMODULE NtDllModule
;
1799 TCHAR commandline
[CMDLINE_LENGTH
];
1800 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 ConSetScreenColor(GetStdHandle(STD_OUTPUT_HANDLE
), wDefColor
, TRUE
);
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
);