2 * CMD.C - command-line interface.
7 * 17 Jun 1994 (Tim Norman)
10 * 08 Aug 1995 (Matt Rains)
11 * I have cleaned up the source code. changes now bring this source
12 * into guidelines for recommended programming practice.
14 * A added the the standard FreeDOS GNU licence test to the
15 * initialize() function.
17 * Started to replace puts() with printf(). this will help
18 * standardize output. please follow my lead.
20 * I have added some constants to help making changes easier.
22 * 15 Dec 1995 (Tim Norman)
23 * major rewrite of the code to make it more efficient and add
24 * redirection support (finally!)
26 * 06 Jan 1996 (Tim Norman)
27 * finished adding redirection support! Changed to use our own
28 * exec code (MUCH thanks to Svante Frey!!)
30 * 29 Jan 1996 (Tim Norman)
31 * added support for CHDIR, RMDIR, MKDIR, and ERASE, as per
32 * suggestion of Steffan Kaiser
34 * changed "file not found" error message to "bad command or
35 * filename" thanks to Dustin Norman for noticing that confusing
38 * changed the format to call internal commands (again) so that if
39 * they want to split their commands, they can do it themselves
40 * (none of the internal functions so far need that much power, anyway)
42 * 27 Aug 1996 (Tim Norman)
43 * added in support for Oliver Mueller's ALIAS command
45 * 14 Jun 1997 (Steffan Kaiser)
46 * added ctrl-break handling and error level
48 * 16 Jun 1998 (Rob Lake)
49 * Runs command.com if /P is specified in command line. Command.com
50 * also stays permanent. If /C is in the command line, starts the
51 * program next in the line.
53 * 21 Jun 1998 (Rob Lake)
54 * Fixed up /C so that arguments for the program
56 * 08-Jul-1998 (John P. Price)
57 * Now sets COMSPEC environment variable
58 * misc clean up and optimization
59 * added date and time commands
60 * changed to using spawnl instead of exec. exec does not copy the
61 * environment to the child process!
63 * 14 Jul 1998 (Hans B Pufal)
64 * Reorganised source to be more efficient and to more closely
65 * follow MS-DOS conventions. (eg %..% environment variable
66 * replacement works form command line as well as batch file.
68 * New organisation also properly support nested batch files.
70 * New command table structure is half way towards providing a
71 * system in which COMMAND will find out what internal commands
74 * 24 Jul 1998 (Hans B Pufal) [HBP_003]
75 * Fixed return value when called with /C option
77 * 27 Jul 1998 John P. Price
78 * added config.h include
80 * 28 Jul 1998 John P. Price
81 * added showcmds function to show commands and options available
83 * 07-Aug-1998 (John P Price <linux-guru@gcfl.net>)
84 * Fixed carrage return output to better match MSDOS with echo
85 * on or off. (marked with "JPP 19980708")
87 * 07-Dec-1998 (Eric Kohl)
88 * First ReactOS release.
89 * Extended length of commandline buffers to 512.
91 * 13-Dec-1998 (Eric Kohl)
92 * Added COMSPEC environment variable.
93 * Added "/t" support (color) on cmd command line.
95 * 07-Jan-1999 (Eric Kohl)
96 * Added help text ("cmd /?").
98 * 25-Jan-1999 (Eric Kohl)
99 * Unicode and redirection safe!
100 * Fixed redirections and piping.
101 * Piping is based on temporary files, but basic support
102 * for anonymous pipes already exists.
104 * 27-Jan-1999 (Eric Kohl)
105 * Replaced spawnl() by CreateProcess().
107 * 22-Oct-1999 (Eric Kohl)
108 * Added break handler.
110 * 15-Dec-1999 (Eric Kohl)
111 * Fixed current directory
113 * 28-Dec-1999 (Eric Kohl)
114 * Restore window title after program/batch execution
116 * 03-Feb-2001 (Eric Kohl)
117 * Workaround because argc[0] is NULL under ReactOS
119 * 23-Feb-2001 (Carl Nettelblad <cnettel@hem.passagen.se>)
120 * %envvar% replacement conflicted with for.
122 * 30-Apr-2004 (Filip Navara <xnavara@volny.cz>)
123 * Make MakeSureDirectoryPathExistsEx unicode safe.
126 * Removed MakeSureDirectoryPathExistsEx.
127 * Use the current directory if GetTempPath fails.
129 * 12-Jul-2004 (Jens Collin <jens.collin@lakhei.com>)
130 * Added ShellExecute call when all else fails to be able to "launch" any file.
132 * 02-Apr-2005 (Magnus Olsen <magnus@greatlord.com>)
133 * Remove all hardcode string to En.rc
135 * 06-May-2005 (Klemens Friedl <frik85@gmail.com>)
136 * Add 'help' command (list all commands plus description)
138 * 06-jul-2005 (Magnus Olsen <magnus@greatlord.com>)
139 * translate '%errorlevel%' to the internal value.
140 * Add proper memmory alloc ProcessInput, the error
141 * handling for memmory handling need to be improve
147 #define NT_SUCCESS(StatCode) ((NTSTATUS)(StatCode) >= 0)
150 typedef NTSTATUS (WINAPI
*NtQueryInformationProcessProc
)(HANDLE
, PROCESSINFOCLASS
,
151 PVOID
, ULONG
, PULONG
);
152 typedef NTSTATUS (WINAPI
*NtReadVirtualMemoryProc
)(HANDLE
, PVOID
, PVOID
, ULONG
, PULONG
);
154 BOOL bExit
= FALSE
; /* indicates EXIT was typed */
155 BOOL bCanExit
= TRUE
; /* indicates if this shell is exitable */
156 BOOL bCtrlBreak
= FALSE
; /* Ctrl-Break or Ctrl-C hit */
157 BOOL bIgnoreEcho
= FALSE
; /* Set this to TRUE to prevent a newline, when executing a command */
158 INT nErrorLevel
= 0; /* Errorlevel of last launched external program */
159 BOOL bChildProcessRunning
= FALSE
;
160 DWORD dwChildProcessId
= 0;
165 HANDLE CMD_ModuleHandle
;
168 static NtQueryInformationProcessProc NtQueryInformationProcessPtr
= NULL
;
169 static NtReadVirtualMemoryProc NtReadVirtualMemoryPtr
= NULL
;
171 #ifdef INCLUDE_CMD_COLOR
172 WORD wColor
; /* current color */
173 WORD wDefColor
; /* default color */
179 * insert commas into a number
182 ConvertULargeInteger (ULARGE_INTEGER num
, LPTSTR des
, INT len
, BOOL bPutSeperator
)
190 if (num
.QuadPart
== 0)
198 iTarget
= nNumberGroups
;
200 bPutSeperator
= FALSE
;
202 while (num
.QuadPart
> 0)
204 if (iTarget
== n
&& bPutSeperator
)
206 iTarget
+= nNumberGroups
+ 1;
207 temp
[31 - n
++] = cThousandSeparator
;
209 temp
[31 - n
++] = (TCHAR
)(num
.QuadPart
% 10) + _T('0');
215 memcpy(des
, temp
+ 32 - n
, n
* sizeof(TCHAR
));
222 * is character a delimeter when used on first word?
225 static BOOL
IsDelimiter (TCHAR c
)
227 return (c
== _T('/') || c
== _T('=') || c
== _T('\0') || _istspace (c
));
231 * Is a process a console process?
233 static BOOL
IsConsoleProcess(HANDLE Process
)
236 PROCESS_BASIC_INFORMATION Info
;
240 if (NULL
== NtQueryInformationProcessPtr
|| NULL
== NtReadVirtualMemoryPtr
)
245 Status
= NtQueryInformationProcessPtr (
246 Process
, ProcessBasicInformation
,
247 &Info
, sizeof(PROCESS_BASIC_INFORMATION
), NULL
);
248 if (! NT_SUCCESS(Status
))
250 WARN ("NtQueryInformationProcess failed with status %08x\n", Status
);
253 Status
= NtReadVirtualMemoryPtr (
254 Process
, Info
.PebBaseAddress
, &ProcessPeb
,
255 sizeof(PEB
), &BytesRead
);
256 if (! NT_SUCCESS(Status
) || sizeof(PEB
) != BytesRead
)
258 WARN ("Couldn't read virt mem status %08x bytes read %lu\n", Status
, BytesRead
);
262 return IMAGE_SUBSYSTEM_WINDOWS_CUI
== ProcessPeb
.ImageSubSystem
;
268 #define SHELLEXECUTETEXT "ShellExecuteW"
270 #define SHELLEXECUTETEXT "ShellExecuteA"
273 typedef HINSTANCE (WINAPI
*MYEX
)(
277 LPCTSTR lpParameters
,
284 static BOOL
RunFile(LPTSTR filename
)
290 TRACE ("RunFile(%s)\n", debugstr_aw(filename
));
291 hShell32
= LoadLibrary(_T("SHELL32.DLL"));
294 WARN ("RunFile: couldn't load SHELL32.DLL!\n");
298 hShExt
= (MYEX
)(FARPROC
)GetProcAddress(hShell32
, SHELLEXECUTETEXT
);
301 WARN ("RunFile: couldn't find ShellExecuteA/W in SHELL32.DLL!\n");
302 FreeLibrary(hShell32
);
306 TRACE ("RunFile: ShellExecuteA/W is at %x\n", hShExt
);
308 ret
= (hShExt
)(NULL
, _T("open"), filename
, NULL
, NULL
, SW_SHOWNORMAL
);
310 TRACE ("RunFile: ShellExecuteA/W returned %p\n", (DWORD_PTR
)ret
);
312 FreeLibrary(hShell32
);
313 return (((DWORD_PTR
)ret
) > 32);
319 * This command (in first) was not found in the command table
321 * Full - whole command line
322 * First - first word on command line
323 * Rest - rest of command line
327 Execute (LPTSTR Full
, LPTSTR First
, LPTSTR Rest
)
329 TCHAR
*szFullName
=NULL
;
334 TCHAR szWindowTitle
[MAX_PATH
];
335 DWORD dwExitCode
= 0;
337 TRACE ("Execute: \'%s\' \'%s\'\n", debugstr_aw(first
), debugstr_aw(rest
));
339 /* we need biger buffer that First, Rest, Full are already
340 need rewrite some code to use cmd_realloc when it need instead
341 of add 512bytes extra */
343 first
= cmd_alloc ( (_tcslen(First
) + 512) * sizeof(TCHAR
));
346 error_out_of_memory();
351 rest
= cmd_alloc ( (_tcslen(Rest
) + 512) * sizeof(TCHAR
));
355 error_out_of_memory();
360 full
= cmd_alloc ( (_tcslen(Full
) + 512) * sizeof(TCHAR
));
365 error_out_of_memory();
370 szFullName
= cmd_alloc ( (_tcslen(Full
) + 512) * sizeof(TCHAR
));
376 error_out_of_memory();
382 /* Though it was already parsed once, we have a different set of rules
383 for parsing before we pass to CreateProccess */
384 if(!_tcschr(Full
,_T('\"')))
386 _tcscpy(first
,First
);
393 BOOL bInside
= FALSE
;
398 /* find the end of the command and start of the args */
399 for(i
= 0; i
< _tcslen(first
); i
++)
401 if(!_tcsncmp(&first
[i
], _T("\""), 1))
403 if(!_tcsncmp(&first
[i
], _T(" "), 1) && !bInside
)
405 _tcscpy(rest
,&first
[i
]);
412 /* remove any slashes */
413 while(i
< _tcslen(first
))
415 if(first
[i
] == _T('\"'))
416 memmove(&first
[i
],&first
[i
+ 1], _tcslen(&first
[i
]) * sizeof(TCHAR
));
420 /* Drop quotes around it just in case there is a space */
421 _tcscpy(full
,_T("\""));
423 _tcscat(full
,_T("\" "));
427 /* check for a drive change */
428 if ((_istalpha (first
[0])) && (!_tcscmp (first
+ 1, _T(":"))))
431 if (!SetCurrentDirectory(first
))
432 /* Guess they changed disc or something, handle that gracefully and get to root */
439 working
= SetCurrentDirectory(str
);
442 if (!working
) ConErrResPuts (STRING_FREE_ERROR1
);
447 cmd_free (szFullName
);
452 /* get the PATH environment variable and parse it */
453 /* search the PATH environment variable for the binary */
454 if (!SearchForExecutable (first
, szFullName
))
456 error_bad_command ();
460 cmd_free (szFullName
);
466 GetConsoleTitle (szWindowTitle
, MAX_PATH
);
468 /* check if this is a .BAT or .CMD file */
469 dot
= _tcsrchr (szFullName
, _T('.'));
470 if (dot
&& (!_tcsicmp (dot
, _T(".bat")) || !_tcsicmp (dot
, _T(".cmd"))))
472 TRACE ("[BATCH: %s %s]\n", debugstr_aw(szFullName
), debugstr_aw(rest
));
473 Batch (szFullName
, first
, rest
, FALSE
);
477 /* exec the program */
478 PROCESS_INFORMATION prci
;
481 TRACE ("[EXEC: %s %s]\n", debugstr_aw(full
), debugstr_aw(rest
));
482 /* build command line for CreateProcess() */
484 /* fill startup info */
485 memset (&stui
, 0, sizeof (STARTUPINFO
));
486 stui
.cb
= sizeof (STARTUPINFO
);
487 stui
.dwFlags
= STARTF_USESHOWWINDOW
;
488 stui
.wShowWindow
= SW_SHOWDEFAULT
;
490 // return console to standard mode
491 SetConsoleMode (GetStdHandle(STD_INPUT_HANDLE
),
492 ENABLE_LINE_INPUT
| ENABLE_PROCESSED_INPUT
| ENABLE_ECHO_INPUT
);
494 if (CreateProcess (szFullName
,
499 0, /* CREATE_NEW_PROCESS_GROUP */
506 if (IsConsoleProcess(prci
.hProcess
))
508 /* FIXME: Protect this with critical section */
509 bChildProcessRunning
= TRUE
;
510 dwChildProcessId
= prci
.dwProcessId
;
512 WaitForSingleObject (prci
.hProcess
, INFINITE
);
514 /* FIXME: Protect this with critical section */
515 bChildProcessRunning
= FALSE
;
517 GetExitCodeProcess (prci
.hProcess
, &dwExitCode
);
518 nErrorLevel
= (INT
)dwExitCode
;
524 CloseHandle (prci
.hThread
);
525 CloseHandle (prci
.hProcess
);
529 TRACE ("[ShellExecute: %s]\n", debugstr_aw(full
));
530 // See if we can run this with ShellExecute() ie myfile.xls
533 TRACE ("[ShellExecute failed!: %s]\n", debugstr_aw(full
));
534 error_bad_command ();
542 // restore console mode
544 GetStdHandle( STD_INPUT_HANDLE
),
545 ENABLE_PROCESSED_INPUT
);
548 /* Get code page if it has been change */
549 InputCodePage
= GetConsoleCP();
550 OutputCodePage
= GetConsoleOutputCP();
551 SetConsoleTitle (szWindowTitle
);
556 cmd_free (szFullName
);
557 return nErrorLevel
== 0;
562 * look through the internal commands and determine whether or not this
563 * command is one of them. If it is, call the command. If not, call
564 * execute to run it as an external program.
566 * line - the command line of the program to run
571 DoCommand (LPTSTR line
)
573 TCHAR
*com
= NULL
; /* the first word in the command */
576 LPTSTR rest
; /* pointer to the rest of the command line */
581 TRACE ("DoCommand: (\'%s\')\n", debugstr_aw(line
));
583 com
= cmd_alloc( (_tcslen(line
) +512)*sizeof(TCHAR
) );
586 error_out_of_memory();
591 /* Skip over initial white space */
592 while (_istspace (*line
))
598 /* Anything to do ? */
601 if (*rest
== _T('"'))
603 /* treat quoted words specially */
607 while(*rest
!= _T('\0') && *rest
!= _T('"'))
608 *cp
++ = _totlower (*rest
++);
609 if (*rest
== _T('"'))
614 while (!IsDelimiter (*rest
))
615 *cp
++ = _totlower (*rest
++);
619 /* Terminate first word */
622 /* Do not limit commands to MAX_PATH */
624 if(_tcslen(com) > MAX_PATH)
632 /* Skip over whitespace to rest of line, exclude 'echo' command */
633 if (_tcsicmp (com
, _T("echo")))
635 while (_istspace (*rest
))
639 /* Scan internal command table */
640 for (cmdptr
= cmds
;; cmdptr
++)
642 /* If end of table execute ext cmd */
643 if (cmdptr
->name
== NULL
)
645 ret
= Execute (line
, com
, rest
);
649 if (!_tcscmp (com
, cmdptr
->name
))
655 /* The following code handles the case of commands like CD which
656 * are recognised even when the command name and parameter are
657 * not space separated.
663 /* Get length of command name */
664 cl
= _tcslen (cmdptr
->name
);
666 if ((cmdptr
->flags
& CMD_SPECIAL
) &&
667 (!_tcsncmp (cmdptr
->name
, com
, cl
)) &&
668 (_tcschr (_T("\\.-"), *(com
+ cl
))))
670 /* OK its one of the specials...*/
672 /* Call with new rest */
673 cmdptr
->func (cstart
+ cl
);
684 * process the command line and execute the appropriate functions
685 * full input/output redirection and piping are supported
688 VOID
ParseCommandLine (LPTSTR cmd
)
690 PARSED_COMMAND
*Cmd
= ParseCommand(cmd
);
699 ExecutePipeline(PARSED_COMMAND
*Cmd
)
701 #ifdef FEATURE_REDIRECTION
702 TCHAR szTempPath
[MAX_PATH
] = _T(".\\");
703 TCHAR szFileName
[2][MAX_PATH
] = {_T(""), _T("")};
704 HANDLE hFile
[2] = {INVALID_HANDLE_VALUE
, INVALID_HANDLE_VALUE
};
709 #endif /* FEATURE_REDIRECTION */
711 //TRACE ("ParseCommandLine: (\'%s\')\n", debugstr_aw(s));
713 #ifdef FEATURE_REDIRECTION
714 /* find the temp path to store temporary files */
715 Length
= GetTempPath (MAX_PATH
, szTempPath
);
716 if (Length
> 0 && Length
< MAX_PATH
)
718 Attributes
= GetFileAttributes(szTempPath
);
719 if (Attributes
== 0xffffffff ||
720 !(Attributes
& FILE_ATTRIBUTE_DIRECTORY
))
725 if (Length
== 0 || Length
>= MAX_PATH
)
727 _tcscpy(szTempPath
, _T(".\\"));
729 if (szTempPath
[_tcslen (szTempPath
) - 1] != _T('\\'))
730 _tcscat (szTempPath
, _T("\\"));
732 /* Set up the initial conditions ... */
733 /* preserve STDIN and STDOUT handles */
734 hOldConIn
= GetStdHandle (STD_INPUT_HANDLE
);
735 hOldConOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
737 /* Now do all but the last pipe command */
738 *szFileName
[0] = _T('\0');
739 hFile
[0] = INVALID_HANDLE_VALUE
;
741 while (Cmd
->Type
== C_PIPE
)
743 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
745 /* Create unique temporary file name */
746 GetTempFileName (szTempPath
, _T("CMD"), 0, szFileName
[1]);
748 /* we need make sure the LastError msg is zero before calling CreateFile */
751 /* Set current stdout to temporary file */
752 hFile
[1] = CreateFile (szFileName
[1], GENERIC_WRITE
, 0, &sa
,
753 TRUNCATE_EXISTING
, FILE_ATTRIBUTE_TEMPORARY
, NULL
);
755 if (hFile
[1] == INVALID_HANDLE_VALUE
)
757 ConErrResPrintf(STRING_CMD_ERROR2
);
761 SetStdHandle (STD_OUTPUT_HANDLE
, hFile
[1]);
763 ExecuteCommand(Cmd
->Subcommands
);
765 /* close stdout file */
766 SetStdHandle (STD_OUTPUT_HANDLE
, hOldConOut
);
767 if ((hFile
[1] != INVALID_HANDLE_VALUE
) && (hFile
[1] != hOldConOut
))
769 CloseHandle (hFile
[1]);
770 hFile
[1] = INVALID_HANDLE_VALUE
;
773 /* close old stdin file */
774 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
775 if ((hFile
[0] != INVALID_HANDLE_VALUE
) && (hFile
[0] != hOldConIn
))
777 /* delete old stdin file, if it is a real file */
778 CloseHandle (hFile
[0]);
779 hFile
[0] = INVALID_HANDLE_VALUE
;
780 DeleteFile (szFileName
[0]);
781 *szFileName
[0] = _T('\0');
784 /* copy stdout file name to stdin file name */
785 _tcscpy (szFileName
[0], szFileName
[1]);
786 *szFileName
[1] = _T('\0');
788 /* we need make sure the LastError msg is zero before calling CreateFile */
791 /* open new stdin file */
792 hFile
[0] = CreateFile (szFileName
[0], GENERIC_READ
, 0, &sa
,
793 OPEN_EXISTING
, FILE_ATTRIBUTE_TEMPORARY
, NULL
);
794 SetStdHandle (STD_INPUT_HANDLE
, hFile
[0]);
796 Cmd
= Cmd
->Subcommands
->Next
;
799 /* Now set up the end conditions... */
800 SetStdHandle(STD_OUTPUT_HANDLE
, hOldConOut
);
804 /* process final command */
807 #ifdef FEATURE_REDIRECTION
808 /* close old stdin file */
809 #if 0 /* buggy implementation */
810 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
811 if ((hFile
[0] != INVALID_HANDLE_VALUE
) &&
812 (hFile
[0] != hOldConIn
))
814 /* delete old stdin file, if it is a real file */
815 CloseHandle (hFile
[0]);
816 hFile
[0] = INVALID_HANDLE_VALUE
;
817 DeleteFile (szFileName
[0]);
818 *szFileName
[0] = _T('\0');
821 /* Restore original STDIN */
822 if (hOldConIn
!= INVALID_HANDLE_VALUE
)
824 HANDLE hIn
= GetStdHandle (STD_INPUT_HANDLE
);
825 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
826 if (hOldConIn
!= hIn
)
828 hOldConIn
= INVALID_HANDLE_VALUE
;
832 WARN ("Can't restore STDIN! Is invalid!!\n", out
);
834 #endif /* buggy implementation */
837 if (hOldConIn
!= INVALID_HANDLE_VALUE
)
839 HANDLE hIn
= GetStdHandle (STD_INPUT_HANDLE
);
840 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
841 if (hIn
== INVALID_HANDLE_VALUE
)
843 WARN ("Previous STDIN is invalid!!\n");
847 if (GetFileType (hIn
) == FILE_TYPE_DISK
)
851 CloseHandle (hFile
[0]);
852 hFile
[0] = INVALID_HANDLE_VALUE
;
853 DeleteFile (szFileName
[0]);
854 *szFileName
[0] = _T('\0');
858 WARN ("hFile[0] and hIn dont match!!!\n");
863 #endif /* FEATURE_REDIRECTION */
867 ExecuteCommand(PARSED_COMMAND
*Cmd
)
869 BOOL bNewBatch
= TRUE
;
873 if (!PerformRedirection(Cmd
->Redirections
))
882 Success
= DoCommand(Cmd
->CommandLine
);
885 AddBatchRedirection(&Cmd
->Redirections
);
890 for (Sub
= Cmd
->Subcommands
; Sub
; Sub
= Sub
->Next
)
891 Success
= ExecuteCommand(Sub
);
895 Sub
= Cmd
->Subcommands
;
896 Success
= ExecuteCommand(Sub
);
897 if (Success
== (Cmd
->Type
- C_IFFAILURE
))
900 Success
= ExecuteCommand(Sub
);
904 ExecutePipeline(Cmd
);
908 UndoRedirection(Cmd
->Redirections
, NULL
);
913 GrowIfNecessary_dbg ( UINT needed
, LPTSTR
* ret
, UINT
* retlen
, const char *file
, int line
)
915 if ( *ret
&& needed
< *retlen
)
921 *ret
= (LPTSTR
)cmd_alloc_dbg ( *retlen
* sizeof(TCHAR
), file
, line
);
923 *ret
= (LPTSTR
)cmd_alloc ( *retlen
* sizeof(TCHAR
) );
926 SetLastError ( ERROR_OUTOFMEMORY
);
929 #define GrowIfNecessary(x, y, z) GrowIfNecessary_dbg(x, y, z, __FILE__, __LINE__)
932 GetEnvVarOrSpecial ( LPCTSTR varName
)
934 static LPTSTR ret
= NULL
;
935 static UINT retlen
= 0;
938 size
= GetEnvironmentVariable ( varName
, ret
, retlen
);
941 if ( !GrowIfNecessary ( size
, &ret
, &retlen
) )
943 size
= GetEnvironmentVariable ( varName
, ret
, retlen
);
948 /* env var doesn't exist, look for a "special" one */
950 if (_tcsicmp(varName
,_T("cd")) ==0)
952 size
= GetCurrentDirectory ( retlen
, ret
);
955 if ( !GrowIfNecessary ( size
, &ret
, &retlen
) )
957 size
= GetCurrentDirectory ( retlen
, ret
);
964 else if (_tcsicmp(varName
,_T("time")) ==0)
967 if ( !GrowIfNecessary ( MAX_PATH
, &ret
, &retlen
) )
970 _sntprintf ( ret
, retlen
, _T("%02d%c%02d%c%02d%c%02d"),
971 t
.wHour
, cTimeSeparator
, t
.wMinute
, cTimeSeparator
,
972 t
.wSecond
, cDecimalSeparator
, t
.wMilliseconds
/ 10);
976 else if (_tcsicmp(varName
,_T("date")) ==0)
979 if ( !GrowIfNecessary ( GetDateFormat(LOCALE_USER_DEFAULT
, DATE_SHORTDATE
, NULL
, NULL
, NULL
, 0), &ret
, &retlen
) )
982 size
= GetDateFormat(LOCALE_USER_DEFAULT
, DATE_SHORTDATE
, NULL
, NULL
, ret
, retlen
);
990 else if (_tcsicmp(varName
,_T("random")) ==0)
992 if ( !GrowIfNecessary ( MAX_PATH
, &ret
, &retlen
) )
994 /* Get random number */
995 _itot(rand(),ret
,10);
1000 else if (_tcsicmp(varName
,_T("cmdcmdline")) ==0)
1002 return GetCommandLine();
1005 /* %CMDEXTVERSION% */
1006 else if (_tcsicmp(varName
,_T("cmdextversion")) ==0)
1008 if ( !GrowIfNecessary ( MAX_PATH
, &ret
, &retlen
) )
1010 /* Set version number to 2 */
1016 else if (_tcsicmp(varName
,_T("errorlevel")) ==0)
1018 if ( !GrowIfNecessary ( MAX_PATH
, &ret
, &retlen
) )
1020 _itot(nErrorLevel
,ret
,10);
1030 GetBatchVar ( LPCTSTR varName
, UINT
* varNameLen
)
1032 static LPTSTR ret
= NULL
;
1033 static UINT retlen
= 0;
1042 if (_tcsncicmp(varName
, _T("dp0"), 3) == 0)
1045 len
= _tcsrchr(bc
->BatchFilePath
, _T('\\')) + 1 - bc
->BatchFilePath
;
1046 if (!GrowIfNecessary(len
+ 1, &ret
, &retlen
))
1048 memcpy(ret
, bc
->BatchFilePath
, len
* sizeof(TCHAR
));
1049 ret
[len
] = _T('\0');
1054 if (*varName
>= _T('0') && *varName
<= _T('9')) {
1055 LPTSTR arg
= FindArg(*varName
- _T('0'));
1057 if (*arg
!= _T('"'))
1060 /* Exclude the leading and trailing quotes */
1063 if (arg
[len
- 1] == _T('"'))
1066 if (!GrowIfNecessary(len
+ 1, &ret
, &retlen
))
1068 memcpy(ret
, arg
, len
* sizeof(TCHAR
));
1069 ret
[len
] = _T('\0');
1083 return FindArg(*varName
- _T('0'));
1087 // Copy over the raw params(not including the batch file name
1089 return bc
->raw_params
;
1098 SubstituteVars(TCHAR
*Src
, TCHAR
*Dest
, TCHAR Delim
, BOOL bIsBatch
)
1100 #define APPEND(From, Length) { \
1101 if (Dest + (Length) > DestEnd) \
1103 memcpy(Dest, From, (Length) * sizeof(TCHAR)); \
1105 #define APPEND1(Char) { \
1106 if (Dest >= DestEnd) \
1110 TCHAR
*DestEnd
= Dest
+ CMDLINE_LENGTH
- 1;
1124 if (bIsBatch
&& Delim
== _T('%'))
1127 Var
= GetBatchVar(Src
, &NameLen
);
1130 VarLength
= _tcslen(Var
);
1131 APPEND(Var
, VarLength
)
1137 /* Find the end of the variable name. A colon (:) will usually
1138 * end the name and begin the optional modifier, but not if it
1139 * is immediately followed by the delimiter (%VAR:%). */
1141 while (*Src
!= Delim
&& !(*Src
== _T(':') && Src
[1] != Delim
))
1150 Var
= GetEnvVarOrSpecial(SubstStart
);
1154 /* In a batch file, %NONEXISTENT% "expands" to an empty string */
1159 VarLength
= _tcslen(Var
);
1161 if (EndChr
== Delim
)
1163 /* %VAR% - use as-is */
1164 APPEND(Var
, VarLength
)
1166 else if (*Src
== _T('~'))
1168 /* %VAR:~[start][,length]% - substring
1169 * Negative values are offsets from the end */
1170 int Start
= _tcstol(Src
+ 1, &Src
, 0);
1171 int End
= VarLength
;
1174 Start
= max(Start
, 0);
1175 Start
= min(Start
, VarLength
);
1176 if (*Src
== _T(','))
1178 End
= _tcstol(Src
+ 1, &Src
, 0);
1179 End
+= (End
< 0) ? VarLength
: Start
;
1180 End
= max(End
, Start
);
1181 End
= min(End
, VarLength
);
1183 if (*Src
++ != Delim
)
1185 APPEND(&Var
[Start
], End
- Start
);
1189 /* %VAR:old=new% - replace all occurrences of old with new
1190 * %VAR:*old=new% - replace first occurrence only,
1191 * and remove everything before it */
1193 DWORD OldLength
, NewLength
;
1195 int LastMatch
= 0, i
= 0;
1197 if (*Src
== _T('*'))
1203 /* the string to replace may contain the delimiter */
1204 Src
= _tcschr(Old
= Src
, _T('='));
1207 OldLength
= Src
++ - Old
;
1211 Src
= _tcschr(New
= Src
, Delim
);
1214 NewLength
= Src
++ - New
;
1216 while (i
< VarLength
)
1218 if (_tcsnicmp(&Var
[i
], Old
, OldLength
) == 0)
1221 APPEND(&Var
[LastMatch
], i
- LastMatch
)
1222 APPEND(New
, NewLength
)
1231 APPEND(&Var
[LastMatch
], VarLength
- LastMatch
)
1243 ConOutResPrintf(STRING_ALIAS_ERROR
);
1252 * do the prompt/input/process loop
1256 BOOL bNoInteractive
;
1260 ReadLine (TCHAR
*commandline
, BOOL bMore
)
1262 TCHAR readline
[CMDLINE_LENGTH
];
1265 /* if no batch input then... */
1266 if (!(ip
= ReadBatchLine()))
1276 ConOutPrintf(_T("More? "));
1280 /* JPP 19980807 - if echo off, don't print prompt */
1285 ReadCommand (readline
, CMDLINE_LENGTH
- 1);
1286 if (CheckCtrlBreak(BREAK_INPUT
))
1288 ConOutPuts(_T("\n"));
1299 if (!SubstituteVars(ip
, commandline
, _T('%'), bIsBatch
))
1302 /* FIXME: !vars! should be substituted later, after parsing. */
1303 if (!SubstituteVars(commandline
, readline
, _T('!'), bIsBatch
))
1305 _tcscpy(commandline
, readline
);
1311 ProcessInput (BOOL bFlag
)
1313 PARSED_COMMAND
*Cmd
;
1315 bNoInteractive
= bFlag
;
1318 Cmd
= ParseCommand(NULL
);
1323 /* Echo batch file line */
1324 if (bIsBatch
&& bEcho
&& Cmd
->Type
!= C_QUIET
)
1328 ConOutChar(_T('\n'));
1331 ExecuteCommand(Cmd
);
1332 if (bEcho
&& !bIgnoreEcho
&& (!bIsBatch
|| Cmd
->Type
!= C_QUIET
))
1335 bIgnoreEcho
= FALSE
;
1337 while (!bCanExit
|| !bExit
);
1344 * control-break handler.
1346 BOOL WINAPI
BreakHandler (DWORD dwCtrlType
)
1351 static BOOL SelfGenerated
= FALSE
;
1353 if ((dwCtrlType
!= CTRL_C_EVENT
) &&
1354 (dwCtrlType
!= CTRL_BREAK_EVENT
))
1362 SelfGenerated
= FALSE
;
1367 if (bChildProcessRunning
== TRUE
)
1369 SelfGenerated
= TRUE
;
1370 GenerateConsoleCtrlEvent (dwCtrlType
, 0);
1375 rec
.EventType
= KEY_EVENT
;
1376 rec
.Event
.KeyEvent
.bKeyDown
= TRUE
;
1377 rec
.Event
.KeyEvent
.wRepeatCount
= 1;
1378 rec
.Event
.KeyEvent
.wVirtualKeyCode
= _T('C');
1379 rec
.Event
.KeyEvent
.wVirtualScanCode
= _T('C') - 35;
1380 rec
.Event
.KeyEvent
.uChar
.AsciiChar
= _T('C');
1381 rec
.Event
.KeyEvent
.uChar
.UnicodeChar
= _T('C');
1382 rec
.Event
.KeyEvent
.dwControlKeyState
= RIGHT_CTRL_PRESSED
;
1391 /* FIXME: Handle batch files */
1393 //ConOutPrintf(_T("^C"));
1400 VOID
AddBreakHandler (VOID
)
1402 SetConsoleCtrlHandler ((PHANDLER_ROUTINE
)BreakHandler
, TRUE
);
1406 VOID
RemoveBreakHandler (VOID
)
1408 SetConsoleCtrlHandler ((PHANDLER_ROUTINE
)BreakHandler
, FALSE
);
1413 * show commands and options that are available.
1420 /* print command list */
1421 ConOutResPuts(STRING_CMD_HELP1
);
1424 /* print feature list */
1425 ConOutResPuts(STRING_CMD_HELP2
);
1427 #ifdef FEATURE_ALIASES
1428 ConOutResPuts(STRING_CMD_HELP3
);
1430 #ifdef FEATURE_HISTORY
1431 ConOutResPuts(STRING_CMD_HELP4
);
1433 #ifdef FEATURE_UNIX_FILENAME_COMPLETION
1434 ConOutResPuts(STRING_CMD_HELP5
);
1436 #ifdef FEATURE_DIRECTORY_STACK
1437 ConOutResPuts(STRING_CMD_HELP6
);
1439 #ifdef FEATURE_REDIRECTION
1440 ConOutResPuts(STRING_CMD_HELP7
);
1442 ConOutChar(_T('\n'));
1447 ExecuteAutoRunFile (VOID
)
1449 TCHAR autorun
[MAX_PATH
];
1450 DWORD len
= MAX_PATH
;
1453 if( RegOpenKeyEx(HKEY_LOCAL_MACHINE
,
1454 _T("SOFTWARE\\Microsoft\\Command Processor"),
1457 &hkey
) == ERROR_SUCCESS
)
1459 if(RegQueryValueEx(hkey
,
1464 &len
) == ERROR_SUCCESS
)
1466 ParseCommandLine (autorun
);
1474 * set up global initializations and process parameters
1476 * argc - number of parameters to command.com
1477 * argv - command-line parameters
1481 Initialize (int argc
, const TCHAR
* argv
[])
1483 TCHAR commandline
[CMDLINE_LENGTH
];
1484 TCHAR ModuleName
[_MAX_PATH
+ 1];
1489 //TCHAR *ptr, *cmdLine;
1491 /* get version information */
1492 osvi
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
1493 GetVersionEx (&osvi
);
1495 /* Some people like to run ReactOS cmd.exe on Win98, it helps in the
1496 * build process. So don't link implicitly against ntdll.dll, load it
1497 * dynamically instead */
1499 if (osvi
.dwPlatformId
== VER_PLATFORM_WIN32_NT
)
1501 /* ntdll is always present on NT */
1502 NtDllModule
= GetModuleHandle(TEXT("ntdll.dll"));
1506 /* not all 9x versions have a ntdll.dll, try to load it */
1507 NtDllModule
= LoadLibrary(TEXT("ntdll.dll"));
1510 if (NtDllModule
!= NULL
)
1512 NtQueryInformationProcessPtr
= (NtQueryInformationProcessProc
)GetProcAddress(NtDllModule
, "NtQueryInformationProcess");
1513 NtReadVirtualMemoryPtr
= (NtReadVirtualMemoryProc
)GetProcAddress(NtDllModule
, "NtReadVirtualMemory");
1517 TRACE ("[command args:\n");
1518 for (i
= 0; i
< argc
; i
++)
1520 TRACE ("%d. %s\n", i
, debugstr_aw(argv
[i
]));
1526 /* get default input and output console handles */
1527 hOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
1528 hIn
= GetStdHandle (STD_INPUT_HANDLE
);
1530 /* Set EnvironmentVariable PROMPT if it does not exists any env value.
1531 for you can change the EnvirommentVariable for prompt before cmd start
1532 this patch are not 100% right, if it does not exists a PROMPT value cmd should use
1533 $P$G as defualt not set EnvirommentVariable PROMPT to $P$G if it does not exists */
1534 if (GetEnvironmentVariable(_T("PROMPT"),lpBuffer
, sizeof(lpBuffer
) / sizeof(lpBuffer
[0])) == 0)
1535 SetEnvironmentVariable (_T("PROMPT"), _T("$P$G"));
1538 if (argc
>= 2 && !_tcsncmp (argv
[1], _T("/?"), 2))
1540 ConOutResPaging(TRUE
,STRING_CMD_HELP8
);
1543 SetConsoleMode (hIn
, ENABLE_PROCESSED_INPUT
);
1545 #ifdef INCLUDE_CMD_CHDIR
1551 for (i
= 1; i
< argc
; i
++)
1553 if (!_tcsicmp (argv
[i
], _T("/p")))
1555 if (!IsExistingFile (_T("\\autoexec.bat")))
1557 #ifdef INCLUDE_CMD_DATE
1560 #ifdef INCLUDE_CMD_TIME
1566 ParseCommandLine (_T("\\autoexec.bat"));
1570 else if (!_tcsicmp (argv
[i
], _T("/c")))
1572 /* This just runs a program and exits */
1576 _tcscpy (commandline
, argv
[i
]);
1579 _tcscat (commandline
, _T(" "));
1580 _tcscat (commandline
, argv
[i
]);
1583 ParseCommandLine(commandline
);
1584 cmd_exit (ProcessInput (TRUE
));
1591 else if (!_tcsicmp (argv
[i
], _T("/k")))
1593 /* This just runs a program and remains */
1597 _tcscpy (commandline
, _T("\""));
1598 _tcscat (commandline
, argv
[i
]);
1599 _tcscat (commandline
, _T("\""));
1602 _tcscat (commandline
, _T(" "));
1603 _tcscat (commandline
, argv
[i
]);
1605 ParseCommandLine(commandline
);
1608 #ifdef INCLUDE_CMD_COLOR
1609 else if (!_tcsnicmp (argv
[i
], _T("/t:"), 3))
1611 /* process /t (color) argument */
1612 wDefColor
= (WORD
)_tcstoul (&argv
[i
][3], NULL
, 16);
1614 SetScreenColor (wColor
, TRUE
);
1621 /* Display a simple version string */
1622 ConOutPrintf(_T("ReactOS Operating System [Version %s-%s]\n"),
1623 _T(KERNEL_RELEASE_STR
),
1624 _T(KERNEL_VERSION_BUILD_STR
));
1626 ConOutPuts (_T("(C) Copyright 1998-") _T(COPYRIGHT_YEAR
) _T(" ReactOS Team.\n"));
1629 ExecuteAutoRunFile ();
1631 #ifdef FEATURE_DIR_STACK
1632 /* initialize directory stack */
1633 InitDirectoryStack ();
1637 #ifdef FEATURE_HISTORY
1638 /*initialize history*/
1642 /* Set COMSPEC environment variable */
1643 if (0 != GetModuleFileName (NULL
, ModuleName
, _MAX_PATH
+ 1))
1645 ModuleName
[_MAX_PATH
] = _T('\0');
1646 SetEnvironmentVariable (_T("COMSPEC"), ModuleName
);
1649 /* add ctrl break handler */
1654 static VOID
Cleanup (int argc
, const TCHAR
*argv
[])
1656 /* run cmdexit.bat */
1657 if (IsExistingFile (_T("cmdexit.bat")))
1659 ConErrResPuts(STRING_CMD_ERROR5
);
1661 ParseCommandLine (_T("cmdexit.bat"));
1663 else if (IsExistingFile (_T("\\cmdexit.bat")))
1665 ConErrResPuts (STRING_CMD_ERROR5
);
1666 ParseCommandLine (_T("\\cmdexit.bat"));
1669 #ifdef FEATURE_DIECTORY_STACK
1670 /* destroy directory stack */
1671 DestroyDirectoryStack ();
1674 #ifdef INCLUDE_CMD_CHDIR
1678 #ifdef FEATURE_HISTORY
1683 /* remove ctrl break handler */
1684 RemoveBreakHandler ();
1685 SetConsoleMode( GetStdHandle( STD_INPUT_HANDLE
),
1686 ENABLE_LINE_INPUT
| ENABLE_PROCESSED_INPUT
| ENABLE_ECHO_INPUT
);
1688 if (NtDllModule
!= NULL
)
1690 FreeLibrary(NtDllModule
);
1697 int cmd_main (int argc
, const TCHAR
*argv
[])
1699 TCHAR startPath
[MAX_PATH
];
1700 CONSOLE_SCREEN_BUFFER_INFO Info
;
1703 GetCurrentDirectory(MAX_PATH
,startPath
);
1710 hConsole
= CreateFile(_T("CONOUT$"), GENERIC_READ
|GENERIC_WRITE
,
1711 FILE_SHARE_READ
|FILE_SHARE_WRITE
, NULL
,
1712 OPEN_EXISTING
, 0, NULL
);
1713 if (GetConsoleScreenBufferInfo(hConsole
, &Info
) == FALSE
)
1715 ConErrFormatMessage(GetLastError());
1718 wColor
= Info
.wAttributes
;
1721 InputCodePage
= GetConsoleCP();
1722 OutputCodePage
= GetConsoleOutputCP();
1723 CMD_ModuleHandle
= GetModuleHandle(NULL
);
1725 /* check switches on command-line */
1726 Initialize(argc
, argv
);
1728 /* call prompt routine */
1729 nExitCode
= ProcessInput(FALSE
);
1731 /* do the cleanup */
1732 Cleanup(argc
, argv
);
1734 cmd_exit(nExitCode
);