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 0x%p\n", 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
;
874 if (!PerformRedirection(Cmd
->Redirections
))
883 ExpandedLine
= DoDelayedExpansion(Cmd
->Command
.CommandLine
);
889 Success
= DoCommand(ExpandedLine
);
890 cmd_free(ExpandedLine
);
893 AddBatchRedirection(&Cmd
->Redirections
);
898 for (Sub
= Cmd
->Subcommands
; Sub
; Sub
= Sub
->Next
)
899 Success
= ExecuteCommand(Sub
);
903 Sub
= Cmd
->Subcommands
;
904 Success
= ExecuteCommand(Sub
);
905 if (Success
== (Cmd
->Type
- C_IFFAILURE
))
908 Success
= ExecuteCommand(Sub
);
912 ExecutePipeline(Cmd
);
915 Success
= ExecuteIf(Cmd
);
918 Success
= ExecuteFor(Cmd
);
922 UndoRedirection(Cmd
->Redirections
, NULL
);
927 GrowIfNecessary_dbg ( UINT needed
, LPTSTR
* ret
, UINT
* retlen
, const char *file
, int line
)
929 if ( *ret
&& needed
< *retlen
)
935 *ret
= (LPTSTR
)cmd_alloc_dbg ( *retlen
* sizeof(TCHAR
), file
, line
);
937 *ret
= (LPTSTR
)cmd_alloc ( *retlen
* sizeof(TCHAR
) );
940 SetLastError ( ERROR_OUTOFMEMORY
);
943 #define GrowIfNecessary(x, y, z) GrowIfNecessary_dbg(x, y, z, __FILE__, __LINE__)
946 GetEnvVarOrSpecial ( LPCTSTR varName
)
948 static LPTSTR ret
= NULL
;
949 static UINT retlen
= 0;
952 size
= GetEnvironmentVariable ( varName
, ret
, retlen
);
955 if ( !GrowIfNecessary ( size
, &ret
, &retlen
) )
957 size
= GetEnvironmentVariable ( varName
, ret
, retlen
);
962 /* env var doesn't exist, look for a "special" one */
964 if (_tcsicmp(varName
,_T("cd")) ==0)
966 size
= GetCurrentDirectory ( retlen
, ret
);
969 if ( !GrowIfNecessary ( size
, &ret
, &retlen
) )
971 size
= GetCurrentDirectory ( retlen
, ret
);
978 else if (_tcsicmp(varName
,_T("time")) ==0)
981 if ( !GrowIfNecessary ( MAX_PATH
, &ret
, &retlen
) )
984 _sntprintf ( ret
, retlen
, _T("%02d%c%02d%c%02d%c%02d"),
985 t
.wHour
, cTimeSeparator
, t
.wMinute
, cTimeSeparator
,
986 t
.wSecond
, cDecimalSeparator
, t
.wMilliseconds
/ 10);
990 else if (_tcsicmp(varName
,_T("date")) ==0)
993 if ( !GrowIfNecessary ( GetDateFormat(LOCALE_USER_DEFAULT
, DATE_SHORTDATE
, NULL
, NULL
, NULL
, 0), &ret
, &retlen
) )
996 size
= GetDateFormat(LOCALE_USER_DEFAULT
, DATE_SHORTDATE
, NULL
, NULL
, ret
, retlen
);
1004 else if (_tcsicmp(varName
,_T("random")) ==0)
1006 if ( !GrowIfNecessary ( MAX_PATH
, &ret
, &retlen
) )
1008 /* Get random number */
1009 _itot(rand(),ret
,10);
1014 else if (_tcsicmp(varName
,_T("cmdcmdline")) ==0)
1016 return GetCommandLine();
1019 /* %CMDEXTVERSION% */
1020 else if (_tcsicmp(varName
,_T("cmdextversion")) ==0)
1022 if ( !GrowIfNecessary ( MAX_PATH
, &ret
, &retlen
) )
1024 /* Set version number to 2 */
1030 else if (_tcsicmp(varName
,_T("errorlevel")) ==0)
1032 if ( !GrowIfNecessary ( MAX_PATH
, &ret
, &retlen
) )
1034 _itot(nErrorLevel
,ret
,10);
1044 GetBatchVar ( LPCTSTR varName
, UINT
* varNameLen
)
1046 static LPTSTR ret
= NULL
;
1047 static UINT retlen
= 0;
1056 if (_tcsncicmp(varName
, _T("dp0"), 3) == 0)
1059 len
= _tcsrchr(bc
->BatchFilePath
, _T('\\')) + 1 - bc
->BatchFilePath
;
1060 if (!GrowIfNecessary(len
+ 1, &ret
, &retlen
))
1062 memcpy(ret
, bc
->BatchFilePath
, len
* sizeof(TCHAR
));
1063 ret
[len
] = _T('\0');
1068 if (*varName
>= _T('0') && *varName
<= _T('9')) {
1069 LPTSTR arg
= FindArg(*varName
- _T('0'));
1071 if (*arg
!= _T('"'))
1074 /* Exclude the leading and trailing quotes */
1077 if (arg
[len
- 1] == _T('"'))
1080 if (!GrowIfNecessary(len
+ 1, &ret
, &retlen
))
1082 memcpy(ret
, arg
, len
* sizeof(TCHAR
));
1083 ret
[len
] = _T('\0');
1097 return FindArg(*varName
- _T('0'));
1101 // Copy over the raw params(not including the batch file name
1103 return bc
->raw_params
;
1111 BOOL bNoInteractive
;
1115 SubstituteVars(TCHAR
*Src
, TCHAR
*Dest
, TCHAR Delim
)
1117 #define APPEND(From, Length) { \
1118 if (Dest + (Length) > DestEnd) \
1120 memcpy(Dest, From, (Length) * sizeof(TCHAR)); \
1122 #define APPEND1(Char) { \
1123 if (Dest >= DestEnd) \
1127 TCHAR
*DestEnd
= Dest
+ CMDLINE_LENGTH
- 1;
1141 if (bIsBatch
&& Delim
== _T('%'))
1144 Var
= GetBatchVar(Src
, &NameLen
);
1147 VarLength
= _tcslen(Var
);
1148 APPEND(Var
, VarLength
)
1154 /* Find the end of the variable name. A colon (:) will usually
1155 * end the name and begin the optional modifier, but not if it
1156 * is immediately followed by the delimiter (%VAR:%). */
1158 while (*Src
!= Delim
&& !(*Src
== _T(':') && Src
[1] != Delim
))
1167 Var
= GetEnvVarOrSpecial(SubstStart
);
1171 /* In a batch file, %NONEXISTENT% "expands" to an empty string */
1176 VarLength
= _tcslen(Var
);
1178 if (EndChr
== Delim
)
1180 /* %VAR% - use as-is */
1181 APPEND(Var
, VarLength
)
1183 else if (*Src
== _T('~'))
1185 /* %VAR:~[start][,length]% - substring
1186 * Negative values are offsets from the end */
1187 int Start
= _tcstol(Src
+ 1, &Src
, 0);
1188 int End
= VarLength
;
1191 Start
= max(Start
, 0);
1192 Start
= min(Start
, VarLength
);
1193 if (*Src
== _T(','))
1195 End
= _tcstol(Src
+ 1, &Src
, 0);
1196 End
+= (End
< 0) ? VarLength
: Start
;
1197 End
= max(End
, Start
);
1198 End
= min(End
, VarLength
);
1200 if (*Src
++ != Delim
)
1202 APPEND(&Var
[Start
], End
- Start
);
1206 /* %VAR:old=new% - replace all occurrences of old with new
1207 * %VAR:*old=new% - replace first occurrence only,
1208 * and remove everything before it */
1210 DWORD OldLength
, NewLength
;
1212 int LastMatch
= 0, i
= 0;
1214 if (*Src
== _T('*'))
1220 /* the string to replace may contain the delimiter */
1221 Src
= _tcschr(Old
= Src
, _T('='));
1224 OldLength
= Src
++ - Old
;
1228 Src
= _tcschr(New
= Src
, Delim
);
1231 NewLength
= Src
++ - New
;
1233 while (i
< VarLength
)
1235 if (_tcsnicmp(&Var
[i
], Old
, OldLength
) == 0)
1238 APPEND(&Var
[LastMatch
], i
- LastMatch
)
1239 APPEND(New
, NewLength
)
1248 APPEND(&Var
[LastMatch
], VarLength
- LastMatch
)
1260 ConOutResPrintf(STRING_ALIAS_ERROR
);
1268 SubstituteForVars(TCHAR
*Src
, TCHAR
*Dest
)
1270 TCHAR
*DestEnd
= &Dest
[CMDLINE_LENGTH
- 1];
1273 if (Src
[0] == _T('%') && Src
[1] != _T('\0'))
1275 /* This might be a variable. Search the list of contexts for it */
1276 FOR_CONTEXT
*Ctx
= fc
;
1277 while (Ctx
&& (UINT
)(Src
[1] - Ctx
->firstvar
) >= Ctx
->varcount
)
1282 LPTSTR Value
= Ctx
->values
[Src
[1] - Ctx
->firstvar
];
1283 if (Dest
+ _tcslen(Value
) > DestEnd
)
1285 Dest
= _stpcpy(Dest
, Value
);
1290 /* Not a variable; just copy the character */
1291 if (Dest
>= DestEnd
)
1300 DoDelayedExpansion(LPTSTR Line
)
1302 TCHAR Buf1
[CMDLINE_LENGTH
];
1303 TCHAR Buf2
[CMDLINE_LENGTH
];
1305 /* First, substitute FOR variables */
1306 if (!SubstituteForVars(Line
, Buf1
))
1309 if (!_tcschr(Buf1
, _T('!')))
1310 return cmd_dup(Buf1
);
1312 /* FIXME: Delayed substitutions actually aren't quite the same as
1313 * immediate substitutions. In particular, it's possible to escape
1314 * the exclamation point using ^. */
1315 if (!SubstituteVars(Buf1
, Buf2
, _T('!')))
1317 return cmd_dup(Buf2
);
1322 * do the prompt/input/process loop
1327 ReadLine (TCHAR
*commandline
, BOOL bMore
)
1329 TCHAR readline
[CMDLINE_LENGTH
];
1332 /* if no batch input then... */
1333 if (!(ip
= ReadBatchLine()))
1343 ConOutPrintf(_T("More? "));
1347 /* JPP 19980807 - if echo off, don't print prompt */
1352 ReadCommand (readline
, CMDLINE_LENGTH
- 1);
1353 if (CheckCtrlBreak(BREAK_INPUT
))
1355 ConOutPuts(_T("\n"));
1366 return SubstituteVars(ip
, commandline
, _T('%'));
1370 ProcessInput (BOOL bFlag
)
1372 PARSED_COMMAND
*Cmd
;
1374 bNoInteractive
= bFlag
;
1377 Cmd
= ParseCommand(NULL
);
1382 /* Echo batch file line */
1383 if (bIsBatch
&& bEcho
&& Cmd
->Type
!= C_QUIET
)
1387 ConOutChar(_T('\n'));
1390 ExecuteCommand(Cmd
);
1391 if (bEcho
&& !bIgnoreEcho
&& (!bIsBatch
|| Cmd
->Type
!= C_QUIET
))
1394 bIgnoreEcho
= FALSE
;
1396 while (!bCanExit
|| !bExit
);
1403 * control-break handler.
1405 BOOL WINAPI
BreakHandler (DWORD dwCtrlType
)
1410 static BOOL SelfGenerated
= FALSE
;
1412 if ((dwCtrlType
!= CTRL_C_EVENT
) &&
1413 (dwCtrlType
!= CTRL_BREAK_EVENT
))
1421 SelfGenerated
= FALSE
;
1426 if (bChildProcessRunning
== TRUE
)
1428 SelfGenerated
= TRUE
;
1429 GenerateConsoleCtrlEvent (dwCtrlType
, 0);
1434 rec
.EventType
= KEY_EVENT
;
1435 rec
.Event
.KeyEvent
.bKeyDown
= TRUE
;
1436 rec
.Event
.KeyEvent
.wRepeatCount
= 1;
1437 rec
.Event
.KeyEvent
.wVirtualKeyCode
= _T('C');
1438 rec
.Event
.KeyEvent
.wVirtualScanCode
= _T('C') - 35;
1439 rec
.Event
.KeyEvent
.uChar
.AsciiChar
= _T('C');
1440 rec
.Event
.KeyEvent
.uChar
.UnicodeChar
= _T('C');
1441 rec
.Event
.KeyEvent
.dwControlKeyState
= RIGHT_CTRL_PRESSED
;
1450 /* FIXME: Handle batch files */
1452 //ConOutPrintf(_T("^C"));
1459 VOID
AddBreakHandler (VOID
)
1461 SetConsoleCtrlHandler ((PHANDLER_ROUTINE
)BreakHandler
, TRUE
);
1465 VOID
RemoveBreakHandler (VOID
)
1467 SetConsoleCtrlHandler ((PHANDLER_ROUTINE
)BreakHandler
, FALSE
);
1472 * show commands and options that are available.
1479 /* print command list */
1480 ConOutResPuts(STRING_CMD_HELP1
);
1483 /* print feature list */
1484 ConOutResPuts(STRING_CMD_HELP2
);
1486 #ifdef FEATURE_ALIASES
1487 ConOutResPuts(STRING_CMD_HELP3
);
1489 #ifdef FEATURE_HISTORY
1490 ConOutResPuts(STRING_CMD_HELP4
);
1492 #ifdef FEATURE_UNIX_FILENAME_COMPLETION
1493 ConOutResPuts(STRING_CMD_HELP5
);
1495 #ifdef FEATURE_DIRECTORY_STACK
1496 ConOutResPuts(STRING_CMD_HELP6
);
1498 #ifdef FEATURE_REDIRECTION
1499 ConOutResPuts(STRING_CMD_HELP7
);
1501 ConOutChar(_T('\n'));
1506 ExecuteAutoRunFile (VOID
)
1508 TCHAR autorun
[MAX_PATH
];
1509 DWORD len
= MAX_PATH
;
1512 if( RegOpenKeyEx(HKEY_LOCAL_MACHINE
,
1513 _T("SOFTWARE\\Microsoft\\Command Processor"),
1516 &hkey
) == ERROR_SUCCESS
)
1518 if(RegQueryValueEx(hkey
,
1523 &len
) == ERROR_SUCCESS
)
1525 ParseCommandLine (autorun
);
1532 /* Get the command that comes after a /C or /K switch */
1534 GetCmdLineCommand(TCHAR
*commandline
, TCHAR
*ptr
, BOOL AlwaysStrip
)
1538 while (_istspace(*ptr
))
1541 /* Remove leading quote, find final quote */
1542 if (*ptr
== _T('"') &&
1543 (LastQuote
= _tcsrchr(++ptr
, _T('"'))) != NULL
)
1546 /* Under certain circumstances, all quotes are preserved.
1547 * CMD /? documents these conditions as follows:
1549 * 2. Exactly two quotes
1550 * 3. No "special characters" between the quotes
1551 * (CMD /? says &<>()@^| but parentheses did not
1552 * trigger this rule when I tested them.)
1553 * 4. Whitespace exists between the quotes
1554 * 5. Enclosed string is an executable filename
1556 *LastQuote
= _T('\0');
1557 for (Space
= ptr
+ 1; Space
< LastQuote
; Space
++)
1559 if (_istspace(*Space
)) /* Rule 4 */
1561 if (!AlwaysStrip
&& /* Rule 1 */
1562 !_tcspbrk(ptr
, _T("\"&<>@^|")) && /* Rules 2, 3 */
1563 SearchForExecutable(ptr
, commandline
)) /* Rule 5 */
1565 /* All conditions met: preserve both the quotes */
1566 *LastQuote
= _T('"');
1567 _tcscpy(commandline
, ptr
- 1);
1574 /* The conditions were not met: remove both the
1575 * leading quote and the last quote */
1576 _tcscpy(commandline
, ptr
);
1577 _tcscpy(&commandline
[LastQuote
- ptr
], LastQuote
+ 1);
1581 /* No quotes; just copy */
1582 _tcscpy(commandline
, ptr
);
1586 * set up global initializations and process parameters
1591 TCHAR commandline
[CMDLINE_LENGTH
];
1592 TCHAR ModuleName
[_MAX_PATH
+ 1];
1596 TCHAR
*ptr
, *cmdLine
;
1597 BOOL AlwaysStrip
= FALSE
;
1598 BOOL ShowVersion
= TRUE
;
1600 /* get version information */
1601 osvi
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
1602 GetVersionEx (&osvi
);
1604 /* Some people like to run ReactOS cmd.exe on Win98, it helps in the
1605 * build process. So don't link implicitly against ntdll.dll, load it
1606 * dynamically instead */
1608 if (osvi
.dwPlatformId
== VER_PLATFORM_WIN32_NT
)
1610 /* ntdll is always present on NT */
1611 NtDllModule
= GetModuleHandle(TEXT("ntdll.dll"));
1615 /* not all 9x versions have a ntdll.dll, try to load it */
1616 NtDllModule
= LoadLibrary(TEXT("ntdll.dll"));
1619 if (NtDllModule
!= NULL
)
1621 NtQueryInformationProcessPtr
= (NtQueryInformationProcessProc
)GetProcAddress(NtDllModule
, "NtQueryInformationProcess");
1622 NtReadVirtualMemoryPtr
= (NtReadVirtualMemoryProc
)GetProcAddress(NtDllModule
, "NtReadVirtualMemory");
1625 cmdLine
= GetCommandLine();
1626 TRACE ("[command args: %s]\n", debugstr_aw(cmdLine
));
1630 /* get default input and output console handles */
1631 hOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
1632 hIn
= GetStdHandle (STD_INPUT_HANDLE
);
1634 /* Set EnvironmentVariable PROMPT if it does not exists any env value.
1635 for you can change the EnvirommentVariable for prompt before cmd start
1636 this patch are not 100% right, if it does not exists a PROMPT value cmd should use
1637 $P$G as defualt not set EnvirommentVariable PROMPT to $P$G if it does not exists */
1638 if (GetEnvironmentVariable(_T("PROMPT"),lpBuffer
, sizeof(lpBuffer
) / sizeof(lpBuffer
[0])) == 0)
1639 SetEnvironmentVariable (_T("PROMPT"), _T("$P$G"));
1642 SetConsoleMode (hIn
, ENABLE_PROCESSED_INPUT
);
1644 #ifdef INCLUDE_CMD_CHDIR
1648 for (ptr
= cmdLine
; *ptr
; ptr
++)
1650 if (*ptr
== _T('/'))
1652 if (ptr
[1] == _T('?'))
1654 ConOutResPaging(TRUE
,STRING_CMD_HELP8
);
1657 else if (_totlower(ptr
[1]) == _T('p'))
1659 if (!IsExistingFile (_T("\\autoexec.bat")))
1661 #ifdef INCLUDE_CMD_DATE
1664 #ifdef INCLUDE_CMD_TIME
1670 ParseCommandLine (_T("\\autoexec.bat"));
1674 else if (_totlower(ptr
[1]) == _T('c'))
1676 /* This just runs a program and exits */
1677 GetCmdLineCommand(commandline
, &ptr
[2], AlwaysStrip
);
1678 ParseCommandLine(commandline
);
1679 cmd_exit (ProcessInput (TRUE
));
1681 else if (_totlower(ptr
[1]) == _T('k'))
1683 /* This just runs a program and remains */
1684 GetCmdLineCommand(commandline
, &ptr
[2], AlwaysStrip
);
1685 ParseCommandLine(commandline
);
1686 ShowVersion
= FALSE
;
1689 else if (_totlower(ptr
[1]) == _T('s'))
1693 #ifdef INCLUDE_CMD_COLOR
1694 else if (!_tcsnicmp(ptr
, _T("/t:"), 3))
1696 /* process /t (color) argument */
1697 wDefColor
= (WORD
)_tcstoul(&ptr
[3], &ptr
, 16);
1699 SetScreenColor (wColor
, TRUE
);
1707 /* Display a simple version string */
1708 ConOutPrintf(_T("ReactOS Operating System [Version %s-%s]\n"),
1709 _T(KERNEL_RELEASE_STR
),
1710 _T(KERNEL_VERSION_BUILD_STR
));
1712 ConOutPuts (_T("(C) Copyright 1998-") _T(COPYRIGHT_YEAR
) _T(" ReactOS Team.\n"));
1715 ExecuteAutoRunFile ();
1717 #ifdef FEATURE_DIR_STACK
1718 /* initialize directory stack */
1719 InitDirectoryStack ();
1723 #ifdef FEATURE_HISTORY
1724 /*initialize history*/
1728 /* Set COMSPEC environment variable */
1729 if (0 != GetModuleFileName (NULL
, ModuleName
, _MAX_PATH
+ 1))
1731 ModuleName
[_MAX_PATH
] = _T('\0');
1732 SetEnvironmentVariable (_T("COMSPEC"), ModuleName
);
1735 /* add ctrl break handler */
1740 static VOID
Cleanup()
1742 /* run cmdexit.bat */
1743 if (IsExistingFile (_T("cmdexit.bat")))
1745 ConErrResPuts(STRING_CMD_ERROR5
);
1747 ParseCommandLine (_T("cmdexit.bat"));
1749 else if (IsExistingFile (_T("\\cmdexit.bat")))
1751 ConErrResPuts (STRING_CMD_ERROR5
);
1752 ParseCommandLine (_T("\\cmdexit.bat"));
1755 #ifdef FEATURE_DIECTORY_STACK
1756 /* destroy directory stack */
1757 DestroyDirectoryStack ();
1760 #ifdef INCLUDE_CMD_CHDIR
1764 #ifdef FEATURE_HISTORY
1769 /* remove ctrl break handler */
1770 RemoveBreakHandler ();
1771 SetConsoleMode( GetStdHandle( STD_INPUT_HANDLE
),
1772 ENABLE_LINE_INPUT
| ENABLE_PROCESSED_INPUT
| ENABLE_ECHO_INPUT
);
1774 if (NtDllModule
!= NULL
)
1776 FreeLibrary(NtDllModule
);
1783 int cmd_main (int argc
, const TCHAR
*argv
[])
1785 TCHAR startPath
[MAX_PATH
];
1786 CONSOLE_SCREEN_BUFFER_INFO Info
;
1789 GetCurrentDirectory(MAX_PATH
,startPath
);
1796 hConsole
= CreateFile(_T("CONOUT$"), GENERIC_READ
|GENERIC_WRITE
,
1797 FILE_SHARE_READ
|FILE_SHARE_WRITE
, NULL
,
1798 OPEN_EXISTING
, 0, NULL
);
1799 if (GetConsoleScreenBufferInfo(hConsole
, &Info
) == FALSE
)
1801 ConErrFormatMessage(GetLastError());
1804 wColor
= Info
.wAttributes
;
1807 InputCodePage
= GetConsoleCP();
1808 OutputCodePage
= GetConsoleOutputCP();
1809 CMD_ModuleHandle
= GetModuleHandle(NULL
);
1811 /* check switches on command-line */
1814 /* call prompt routine */
1815 nExitCode
= ProcessInput(FALSE
);
1817 /* do the cleanup */
1820 cmd_exit(nExitCode
);