1 /* $Id: cmd.c,v 1.15 2004/06/06 17:33:13 hbirr Exp $
3 * CMD.C - command-line interface.
8 * 17 Jun 1994 (Tim Norman)
11 * 08 Aug 1995 (Matt Rains)
12 * I have cleaned up the source code. changes now bring this source
13 * into guidelines for recommended programming practice.
15 * A added the the standard FreeDOS GNU licence test to the
16 * initialize() function.
18 * Started to replace puts() with printf(). this will help
19 * standardize output. please follow my lead.
21 * I have added some constants to help making changes easier.
23 * 15 Dec 1995 (Tim Norman)
24 * major rewrite of the code to make it more efficient and add
25 * redirection support (finally!)
27 * 06 Jan 1996 (Tim Norman)
28 * finished adding redirection support! Changed to use our own
29 * exec code (MUCH thanks to Svante Frey!!)
31 * 29 Jan 1996 (Tim Norman)
32 * added support for CHDIR, RMDIR, MKDIR, and ERASE, as per
33 * suggestion of Steffan Kaiser
35 * changed "file not found" error message to "bad command or
36 * filename" thanks to Dustin Norman for noticing that confusing
39 * changed the format to call internal commands (again) so that if
40 * they want to split their commands, they can do it themselves
41 * (none of the internal functions so far need that much power, anyway)
43 * 27 Aug 1996 (Tim Norman)
44 * added in support for Oliver Mueller's ALIAS command
46 * 14 Jun 1997 (Steffan Kaiser)
47 * added ctrl-break handling and error level
49 * 16 Jun 1998 (Rob Lake)
50 * Runs command.com if /P is specified in command line. Command.com
51 * also stays permanent. If /C is in the command line, starts the
52 * program next in the line.
54 * 21 Jun 1998 (Rob Lake)
55 * Fixed up /C so that arguments for the program
57 * 08-Jul-1998 (John P. Price)
58 * Now sets COMSPEC environment variable
59 * misc clean up and optimization
60 * added date and time commands
61 * changed to using spawnl instead of exec. exec does not copy the
62 * environment to the child process!
64 * 14 Jul 1998 (Hans B Pufal)
65 * Reorganised source to be more efficient and to more closely
66 * follow MS-DOS conventions. (eg %..% environment variable
67 * replacement works form command line as well as batch file.
69 * New organisation also properly support nested batch files.
71 * New command table structure is half way towards providing a
72 * system in which COMMAND will find out what internal commands
75 * 24 Jul 1998 (Hans B Pufal) [HBP_003]
76 * Fixed return value when called with /C option
78 * 27 Jul 1998 John P. Price
79 * added config.h include
81 * 28 Jul 1998 John P. Price
82 * added showcmds function to show commands and options available
84 * 07-Aug-1998 (John P Price <linux-guru@gcfl.net>)
85 * Fixed carrage return output to better match MSDOS with echo
86 * on or off. (marked with "JPP 19980708")
88 * 07-Dec-1998 (Eric Kohl <ekohl@abo.rhein-zeitung.de>)
89 * First ReactOS release.
90 * Extended length of commandline buffers to 512.
92 * 13-Dec-1998 (Eric Kohl <ekohl@abo.rhein-zeitung.de>)
93 * Added COMSPEC environment variable.
94 * Added "/t" support (color) on cmd command line.
96 * 07-Jan-1999 (Eric Kohl <ekohl@abo.rhein-zeitung.de>)
97 * Added help text ("cmd /?").
99 * 25-Jan-1999 (Eric Kohl <ekohl@abo.rhein-zeitung.de>)
100 * Unicode and redirection safe!
101 * Fixed redirections and piping.
102 * Piping is based on temporary files, but basic support
103 * for anonymous pipes already exists.
105 * 27-Jan-1999 (Eric Kohl <ekohl@abo.rhein-zeitung.de>)
106 * Replaced spawnl() by CreateProcess().
108 * 22-Oct-1999 (Eric Kohl <ekohl@abo.rhein-zeitung.de>)
109 * Added break handler.
111 * 15-Dec-1999 (Eric Kohl <ekohl@abo.rhein-zeitung.de>)
112 * Fixed current directory
114 * 28-Dec-1999 (Eric Kohl <ekohl@abo.rhein-zeitung.de>)
115 * Restore window title after program/batch execution
117 * 03-Feb-2001 (Eric Kohl <ekohl@rz-online.de>)
118 * Workaround because argc[0] is NULL under ReactOS
120 * 23-Feb-2001 (Carl Nettelblad <cnettel@hem.passagen.se>)
121 * %envvar% replacement conflicted with for.
123 * 30-Apr-2004 (Filip Navara <xnavara@volny.cz>)
124 * Make MakeSureDirectoryPathExistsEx unicode safe.
126 * 28-Mai-2004 (Hartmut Birr)
127 * Removed MakeSureDirectoryPathExistsEx.
128 * Use the current directory if GetTempPath fails.
140 #include <winternl.h>
143 #define NT_SUCCESS(StatCode) ((NTSTATUS)(StatCode) >= 0)
149 typedef NTSTATUS (STDCALL
*NtQueryInformationProcessProc
)(HANDLE
, PROCESSINFOCLASS
,
150 PVOID
, ULONG
, PULONG
);
151 typedef NTSTATUS (STDCALL
*NtReadVirtualMemoryProc
)(HANDLE
, PVOID
, PVOID
, ULONG
, PULONG
);
153 BOOL bExit
= FALSE
; /* indicates EXIT was typed */
154 BOOL bCanExit
= TRUE
; /* indicates if this shell is exitable */
155 BOOL bCtrlBreak
= FALSE
; /* Ctrl-Break or Ctrl-C hit */
156 BOOL bIgnoreEcho
= FALSE
; /* Ignore 'newline' before 'cls' */
157 INT nErrorLevel
= 0; /* Errorlevel of last launched external program */
158 BOOL bChildProcessRunning
= FALSE
;
159 DWORD dwChildProcessId
= 0;
165 static NtQueryInformationProcessProc NtQueryInformationProcessPtr
;
166 static NtReadVirtualMemoryProc NtReadVirtualMemoryPtr
;
167 static BOOL NtDllChecked
= FALSE
;
169 #ifdef INCLUDE_CMD_COLOR
170 WORD wColor
; /* current color */
171 WORD wDefColor
; /* default color */
175 * is character a delimeter when used on first word?
179 static BOOL
IsDelimiter (TCHAR c
)
181 return (c
== _T('/') || c
== _T('=') || c
== _T('\0') || _istspace (c
));
185 * Is a process a console process?
187 static BOOL
IsConsoleProcess(HANDLE Process
)
190 PROCESS_BASIC_INFORMATION Info
;
195 /* Some people like to run ReactOS cmd.exe on Win98, it helps in the
196 build process. So don't link implicitly against ntdll.dll, load it
197 dynamically instead */
201 NtDllModule
= LoadLibrary(_T("ntdll.dll"));
202 if (NULL
== NtDllModule
)
204 /* Probably non-WinNT system. Just wait for the commands
206 NtQueryInformationProcessPtr
= NULL
;
207 NtReadVirtualMemoryPtr
= NULL
;
210 NtQueryInformationProcessPtr
= (NtQueryInformationProcessProc
)
211 GetProcAddress(NtDllModule
, "NtQueryInformationProcess");
212 NtReadVirtualMemoryPtr
= (NtReadVirtualMemoryProc
)
213 GetProcAddress(NtDllModule
, "NtReadVirtualMemory");
216 if (NULL
== NtQueryInformationProcessPtr
|| NULL
== NtReadVirtualMemoryPtr
)
221 Status
= NtQueryInformationProcessPtr(Process
, ProcessBasicInformation
,
222 &Info
, sizeof(PROCESS_BASIC_INFORMATION
), NULL
);
223 if (! NT_SUCCESS(Status
))
226 DebugPrintf (_T("NtQueryInformationProcess failed with status %08x\n"), Status
);
230 Status
= NtReadVirtualMemoryPtr(Process
, Info
.PebBaseAddress
, &ProcessPeb
,
231 sizeof(PEB
), &BytesRead
);
232 if (! NT_SUCCESS(Status
) || sizeof(PEB
) != BytesRead
)
235 DebugPrintf (_T("Couldn't read virt mem status %08x bytes read %lu\n"), Status
, BytesRead
);
240 return IMAGE_SUBSYSTEM_WINDOWS_CUI
== ProcessPeb
.ImageSubSystem
;
245 * This command (in first) was not found in the command table
247 * first - first word on command line
248 * rest - rest of command line
252 Execute (LPTSTR full
, LPTSTR first
, LPTSTR rest
)
254 TCHAR szFullName
[MAX_PATH
];
256 TCHAR szWindowTitle
[MAX_PATH
];
258 DWORD dwExitCode
= 0;
261 DebugPrintf (_T("Execute: \'%s\' \'%s\'\n"), first
, rest
);
264 /* check for a drive change */
265 if ((_istalpha (first
[0])) && (!_tcscmp (first
+ 1, _T(":"))))
268 if (!SetCurrentDirectory(first
))
269 /* Guess they changed disc or something, handle that gracefully and get to root */
276 working
= SetCurrentDirectory(str
);
279 if (!working
) ConErrPuts (INVALIDDRIVE
);
284 /* get the PATH environment variable and parse it */
285 /* search the PATH environment variable for the binary */
286 if (!SearchForExecutable (first
, szFullName
))
288 error_bad_command ();
293 GetConsoleTitle (szWindowTitle
, MAX_PATH
);
296 /* check if this is a .BAT or .CMD file */
297 if (!_tcsicmp (_tcsrchr (szFullName
, _T('.')), _T(".bat")) ||
298 !_tcsicmp (_tcsrchr (szFullName
, _T('.')), _T(".cmd")))
301 DebugPrintf (_T("[BATCH: %s %s]\n"), szFullName
, rest
);
303 Batch (szFullName
, first
, rest
);
307 /* exec the program */
308 PROCESS_INFORMATION prci
;
312 DebugPrintf (_T("[EXEC: %s %s]\n"), full
, rest
);
314 /* build command line for CreateProcess() */
316 /* fill startup info */
317 memset (&stui
, 0, sizeof (STARTUPINFO
));
318 stui
.cb
= sizeof (STARTUPINFO
);
319 stui
.dwFlags
= STARTF_USESHOWWINDOW
;
320 stui
.wShowWindow
= SW_SHOWDEFAULT
;
322 // return console to standard mode
323 SetConsoleMode (GetStdHandle(STD_INPUT_HANDLE
),
324 ENABLE_LINE_INPUT
| ENABLE_PROCESSED_INPUT
| ENABLE_ECHO_INPUT
);
326 if (CreateProcess (szFullName
,
331 CREATE_NEW_PROCESS_GROUP
,
337 if (IsConsoleProcess(prci
.hProcess
))
339 /* FIXME: Protect this with critical section */
340 bChildProcessRunning
= TRUE
;
341 dwChildProcessId
= prci
.dwProcessId
;
343 WaitForSingleObject (prci
.hProcess
, INFINITE
);
345 /* FIXME: Protect this with critical section */
346 bChildProcessRunning
= FALSE
;
348 GetExitCodeProcess (prci
.hProcess
, &dwExitCode
);
349 nErrorLevel
= (INT
)dwExitCode
;
351 CloseHandle (prci
.hThread
);
352 CloseHandle (prci
.hProcess
);
356 ErrorMessage (GetLastError (),
357 _T("Error executing CreateProcess()!!\n"));
359 // restore console mode
360 SetConsoleMode( GetStdHandle( STD_INPUT_HANDLE
),
361 ENABLE_PROCESSED_INPUT
);
365 SetConsoleTitle (szWindowTitle
);
371 * look through the internal commands and determine whether or not this
372 * command is one of them. If it is, call the command. If not, call
373 * execute to run it as an external program.
375 * line - the command line of the program to run
380 DoCommand (LPTSTR line
)
382 TCHAR com
[CMDLINE_LENGTH
]; /* the first word in the command */
385 LPTSTR rest
; /* pointer to the rest of the command line */
390 DebugPrintf (_T("DoCommand: (\'%s\')\n"), line
);
393 /* Skip over initial white space */
394 while (_istspace (*line
))
400 /* Anything to do ? */
403 if (*rest
== _T('"'))
405 /* treat quoted words specially */
409 while(*rest
!= _T('\0') && *rest
!= _T('"'))
410 *cp
++ = _totlower (*rest
++);
411 if (*rest
== _T('"'))
416 while (!IsDelimiter (*rest
))
417 *cp
++ = _totlower (*rest
++);
421 /* Terminate first word */
424 /* commands are limited to MAX_PATH */
425 if(_tcslen(com
) > MAX_PATH
)
431 /* Skip over whitespace to rest of line */
432 while (_istspace (*rest
))
435 /* Scan internal command table */
436 for (cmdptr
= cmds
;; cmdptr
++)
438 /* If end of table execute ext cmd */
439 if (cmdptr
->name
== NULL
)
441 Execute (line
, com
, rest
);
445 if (!_tcscmp (com
, cmdptr
->name
))
447 cmdptr
->func (com
, rest
);
451 /* The following code handles the case of commands like CD which
452 * are recognised even when the command name and parameter are
453 * not space separated.
459 /* Get length of command name */
460 cl
= _tcslen (cmdptr
->name
);
462 if ((cmdptr
->flags
& CMD_SPECIAL
) &&
463 (!_tcsncmp (cmdptr
->name
, com
, cl
)) &&
464 (_tcschr (_T("\\.-"), *(com
+ cl
))))
466 /* OK its one of the specials...*/
468 /* Terminate first word properly */
471 /* Call with new rest */
472 cmdptr
->func (com
, cstart
+ cl
);
481 * process the command line and execute the appropriate functions
482 * full input/output redirection and piping are supported
485 VOID
ParseCommandLine (LPTSTR cmd
)
487 TCHAR cmdline
[CMDLINE_LENGTH
];
489 #ifdef FEATURE_REDIRECTION
490 TCHAR in
[CMDLINE_LENGTH
] = _T("");
491 TCHAR out
[CMDLINE_LENGTH
] = _T("");
492 TCHAR err
[CMDLINE_LENGTH
] = _T("");
493 TCHAR szTempPath
[MAX_PATH
] = _T(".\\");
494 TCHAR szFileName
[2][MAX_PATH
] = {_T(""), _T("")};
495 HANDLE hFile
[2] = {INVALID_HANDLE_VALUE
, INVALID_HANDLE_VALUE
};
505 #endif /* FEATURE_REDIRECTION */
507 _tcscpy (cmdline
, cmd
);
511 DebugPrintf (_T("ParseCommandLine: (\'%s\')\n"), s
);
514 #ifdef FEATURE_ALIASES
515 /* expand all aliases */
516 ExpandAlias (s
, CMDLINE_LENGTH
);
517 #endif /* FEATURE_ALIAS */
519 #ifdef FEATURE_REDIRECTION
520 /* find the temp path to store temporary files */
521 Length
= GetTempPath (MAX_PATH
, szTempPath
);
522 if (Length
> 0 && Length
< MAX_PATH
)
524 Attributes
= GetFileAttributes(szTempPath
);
525 if (Attributes
== 0xffffffff ||
526 !(Attributes
& FILE_ATTRIBUTE_DIRECTORY
))
531 if (Length
== 0 || Length
>= MAX_PATH
)
533 _tcscpy(szTempPath
, _T(".\\"));
535 if (szTempPath
[_tcslen (szTempPath
) - 1] != _T('\\'))
536 _tcscat (szTempPath
, _T("\\"));
538 /* get the redirections from the command line */
539 num
= GetRedirection (s
, in
, out
, err
, &nRedirFlags
);
541 /* more efficient, but do we really need to do this? */
542 for (t
= in
; _istspace (*t
); t
++)
546 for (t
= out
; _istspace (*t
); t
++)
550 for (t
= err
; _istspace (*t
); t
++)
554 /* Set up the initial conditions ... */
555 /* preserve STDIN, STDOUT and STDERR handles */
556 hOldConIn
= GetStdHandle (STD_INPUT_HANDLE
);
557 hOldConOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
558 hOldConErr
= GetStdHandle (STD_ERROR_HANDLE
);
564 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
566 hFile
= CreateFile (in
, GENERIC_READ
, FILE_SHARE_READ
, &sa
, OPEN_EXISTING
,
567 FILE_ATTRIBUTE_NORMAL
, NULL
);
568 if (hFile
== INVALID_HANDLE_VALUE
)
570 ConErrPrintf (_T("Can't redirect input from file %s\n"), in
);
574 if (!SetStdHandle (STD_INPUT_HANDLE
, hFile
))
576 ConErrPrintf (_T("Can't redirect input from file %s\n"), in
);
580 DebugPrintf (_T("Input redirected from: %s\n"), in
);
584 /* Now do all but the last pipe command */
585 *szFileName
[0] = _T('\0');
586 hFile
[0] = INVALID_HANDLE_VALUE
;
590 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
592 /* Create unique temporary file name */
593 GetTempFileName (szTempPath
, _T("CMD"), 0, szFileName
[1]);
595 /* Set current stdout to temporary file */
596 hFile
[1] = CreateFile (szFileName
[1], GENERIC_WRITE
, 0, &sa
,
597 TRUNCATE_EXISTING
, FILE_ATTRIBUTE_TEMPORARY
, NULL
);
599 if (hFile
[1] == INVALID_HANDLE_VALUE
){
600 ConErrPrintf (_T("Error creating temporary file for pipe data\n"));
604 SetStdHandle (STD_OUTPUT_HANDLE
, hFile
[1]);
608 /* close stdout file */
609 SetStdHandle (STD_OUTPUT_HANDLE
, hOldConOut
);
610 if ((hFile
[1] != INVALID_HANDLE_VALUE
) && (hFile
[1] != hOldConOut
))
612 CloseHandle (hFile
[1]);
613 hFile
[1] = INVALID_HANDLE_VALUE
;
616 /* close old stdin file */
617 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
618 if ((hFile
[0] != INVALID_HANDLE_VALUE
) && (hFile
[0] != hOldConIn
))
620 /* delete old stdin file, if it is a real file */
621 CloseHandle (hFile
[0]);
622 hFile
[0] = INVALID_HANDLE_VALUE
;
623 DeleteFile (szFileName
[0]);
624 *szFileName
[0] = _T('\0');
627 /* copy stdout file name to stdin file name */
628 _tcscpy (szFileName
[0], szFileName
[1]);
629 *szFileName
[1] = _T('\0');
631 /* open new stdin file */
632 hFile
[0] = CreateFile (szFileName
[0], GENERIC_READ
, 0, &sa
,
633 OPEN_EXISTING
, FILE_ATTRIBUTE_TEMPORARY
, NULL
);
634 SetStdHandle (STD_INPUT_HANDLE
, hFile
[0]);
636 s
= s
+ _tcslen (s
) + 1;
639 /* Now set up the end conditions... */
640 /* redirect STDOUT */
643 /* Final output to here */
645 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
647 hFile
= CreateFile (out
, GENERIC_WRITE
, FILE_SHARE_READ
, &sa
,
648 (nRedirFlags
& OUTPUT_APPEND
) ? OPEN_ALWAYS
: CREATE_ALWAYS
,
649 FILE_ATTRIBUTE_NORMAL
, NULL
);
650 if (hFile
== INVALID_HANDLE_VALUE
)
652 ConErrPrintf (_T("Can't redirect to file %s\n"), out
);
656 if (!SetStdHandle (STD_OUTPUT_HANDLE
, hFile
))
658 ConErrPrintf (_T("Can't redirect to file %s\n"), out
);
662 if (nRedirFlags
& OUTPUT_APPEND
)
666 if (GetFileType (hFile
) == FILE_TYPE_DISK
)
667 SetFilePointer (hFile
, 0, &lHighPos
, FILE_END
);
670 DebugPrintf (_T("Output redirected to: %s\n"), out
);
673 else if (hOldConOut
!= INVALID_HANDLE_VALUE
)
675 /* Restore original stdout */
676 HANDLE hOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
677 SetStdHandle (STD_OUTPUT_HANDLE
, hOldConOut
);
678 if (hOldConOut
!= hOut
)
680 hOldConOut
= INVALID_HANDLE_VALUE
;
683 /* redirect STDERR */
686 /* Final output to here */
688 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
690 if (!_tcscmp (err
, out
))
693 DebugPrintf (_T("Stdout and stderr will use the same file!!\n"));
695 DuplicateHandle (GetCurrentProcess (),
696 GetStdHandle (STD_OUTPUT_HANDLE
),
697 GetCurrentProcess (),
698 &hFile
, 0, TRUE
, DUPLICATE_SAME_ACCESS
);
702 hFile
= CreateFile (err
,
706 (nRedirFlags
& ERROR_APPEND
) ? OPEN_ALWAYS
: CREATE_ALWAYS
,
707 FILE_ATTRIBUTE_NORMAL
,
709 if (hFile
== INVALID_HANDLE_VALUE
)
711 ConErrPrintf (_T("Can't redirect to file %s\n"), err
);
715 if (!SetStdHandle (STD_ERROR_HANDLE
, hFile
))
717 ConErrPrintf (_T("Can't redirect to file %s\n"), err
);
721 if (nRedirFlags
& ERROR_APPEND
)
725 if (GetFileType (hFile
) == FILE_TYPE_DISK
)
726 SetFilePointer (hFile
, 0, &lHighPos
, FILE_END
);
729 DebugPrintf (_T("Error redirected to: %s\n"), err
);
732 else if (hOldConErr
!= INVALID_HANDLE_VALUE
)
734 /* Restore original stderr */
735 HANDLE hErr
= GetStdHandle (STD_ERROR_HANDLE
);
736 SetStdHandle (STD_ERROR_HANDLE
, hOldConErr
);
737 if (hOldConErr
!= hErr
)
739 hOldConErr
= INVALID_HANDLE_VALUE
;
743 /* process final command */
746 #ifdef FEATURE_REDIRECTION
747 /* close old stdin file */
748 #if 0 /* buggy implementation */
749 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
750 if ((hFile
[0] != INVALID_HANDLE_VALUE
) &&
751 (hFile
[0] != hOldConIn
))
753 /* delete old stdin file, if it is a real file */
754 CloseHandle (hFile
[0]);
755 hFile
[0] = INVALID_HANDLE_VALUE
;
756 DeleteFile (szFileName
[0]);
757 *szFileName
[0] = _T('\0');
760 /* Restore original STDIN */
761 if (hOldConIn
!= INVALID_HANDLE_VALUE
)
763 HANDLE hIn
= GetStdHandle (STD_INPUT_HANDLE
);
764 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
765 if (hOldConIn
!= hIn
)
767 hOldConIn
= INVALID_HANDLE_VALUE
;
772 DebugPrintf (_T("Can't restore STDIN! Is invalid!!\n"), out
);
775 #endif /* buggy implementation */
778 if (hOldConIn
!= INVALID_HANDLE_VALUE
)
780 HANDLE hIn
= GetStdHandle (STD_INPUT_HANDLE
);
781 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
782 if (hIn
== INVALID_HANDLE_VALUE
)
785 DebugPrintf (_T("Previous STDIN is invalid!!\n"));
790 if (GetFileType (hIn
) == FILE_TYPE_DISK
)
794 CloseHandle (hFile
[0]);
795 hFile
[0] = INVALID_HANDLE_VALUE
;
796 DeleteFile (szFileName
[0]);
797 *szFileName
[0] = _T('\0');
802 DebugPrintf (_T("hFile[0] and hIn dont match!!!\n"));
810 /* Restore original STDOUT */
811 if (hOldConOut
!= INVALID_HANDLE_VALUE
)
813 HANDLE hOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
814 SetStdHandle (STD_OUTPUT_HANDLE
, hOldConOut
);
815 if (hOldConOut
!= hOut
)
817 hOldConOut
= INVALID_HANDLE_VALUE
;
820 /* Restore original STDERR */
821 if (hOldConErr
!= INVALID_HANDLE_VALUE
)
823 HANDLE hErr
= GetStdHandle (STD_ERROR_HANDLE
);
824 SetStdHandle (STD_ERROR_HANDLE
, hOldConErr
);
825 if (hOldConErr
!= hErr
)
827 hOldConErr
= INVALID_HANDLE_VALUE
;
829 #endif /* FEATURE_REDIRECTION */
834 * do the prompt/input/process loop
839 ProcessInput (BOOL bFlag
)
841 TCHAR commandline
[CMDLINE_LENGTH
];
842 TCHAR readline
[CMDLINE_LENGTH
];
850 /* if no batch input then... */
851 if (!(ip
= ReadBatchLine (&bEchoThisLine
)))
856 ReadCommand (readline
, CMDLINE_LENGTH
);
858 bEchoThisLine
= FALSE
;
882 if ((tp
= FindArg (*ip
- _T('0'))))
884 cp
= _stpcpy (cp
, tp
);
892 cp
+= _stprintf (cp
, _T("%u"), nErrorLevel
);
897 tp
= _tcschr(ip
, _T('%'));
899 (tp
<= _tcschr(ip
, _T(' ')) - 1))
904 /* FIXME: This is just a quick hack!! */
905 /* Do a proper memory allocation!! */
906 if (GetEnvironmentVariable (ip
, evar
, 512))
907 cp
= _stpcpy (cp
, evar
);
927 /* strip trailing spaces */
928 while ((--cp
>= commandline
) && _istspace (*cp
));
930 *(cp
+ 1) = _T('\0');
933 /* Echo batch file line */
937 ConOutPuts (commandline
);
942 ParseCommandLine (commandline
);
943 if (bEcho
&& !bIgnoreEcho
)
948 while (!bCanExit
|| !bExit
);
955 * control-break handler.
957 BOOL WINAPI
BreakHandler (DWORD dwCtrlType
)
959 if ((dwCtrlType
!= CTRL_C_EVENT
) &&
960 (dwCtrlType
!= CTRL_BREAK_EVENT
))
963 if (bChildProcessRunning
== TRUE
)
965 GenerateConsoleCtrlEvent (CTRL_C_EVENT
,
970 /* FIXME: Handle batch files */
972 /* FIXME: Print "^C" */
979 VOID
AddBreakHandler (VOID
)
981 SetConsoleCtrlHandler ((PHANDLER_ROUTINE
)BreakHandler
, TRUE
);
985 VOID
RemoveBreakHandler (VOID
)
987 SetConsoleCtrlHandler ((PHANDLER_ROUTINE
)BreakHandler
, FALSE
);
992 * show commands and options that are available.
999 /* print command list */
1000 ConOutPrintf (_T("\nInternal commands available:\n"));
1001 PrintCommandList ();
1003 /* print feature list */
1004 ConOutPuts (_T("\nFeatures available:"));
1005 #ifdef FEATURE_ALIASES
1006 ConOutPuts (_T(" [aliases]"));
1008 #ifdef FEATURE_HISTORY
1009 ConOutPuts (_T(" [history]"));
1011 #ifdef FEATURE_UNIX_FILENAME_COMPLETION
1012 ConOutPuts (_T(" [unix filename completion]"));
1014 #ifdef FEATURE_DIRECTORY_STACK
1015 ConOutPuts (_T(" [directory stack]"));
1017 #ifdef FEATURE_REDIRECTION
1018 ConOutPuts (_T(" [redirections and piping]"));
1020 ConOutChar (_T('\n'));
1025 * set up global initializations and process parameters
1027 * argc - number of parameters to command.com
1028 * argv - command-line parameters
1032 Initialize (int argc
, TCHAR
* argv
[])
1034 TCHAR commandline
[CMDLINE_LENGTH
];
1035 TCHAR ModuleName
[_MAX_PATH
+ 1];
1038 //TCHAR *ptr, *cmdLine;
1044 DebugPrintf (_T("[command args:\n"));
1045 for (x
= 0; x
< argc
; x
++)
1047 DebugPrintf (_T("%d. %s\n"), x
, argv
[x
]);
1049 DebugPrintf (_T("]\n"));
1052 /* get version information */
1053 osvi
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
1054 GetVersionEx (&osvi
);
1058 /* get default input and output console handles */
1059 hOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
1060 hIn
= GetStdHandle (STD_INPUT_HANDLE
);
1063 if (argc
>= 2 && !_tcsncmp (argv
[1], _T("/?"), 2))
1065 ConOutPuts (_T("Starts a new instance of the ReactOS command line interpreter.\n"
1067 "CMD [/[C|K] command][/P][/Q][/T:bf]\n"
1069 " /C command Runs the specified command and terminates.\n"
1070 " /K command Runs the specified command and remains.\n"
1071 " /P CMD becomes permanent and runs autoexec.bat\n"
1072 " (cannot be terminated).\n"
1073 " /T:bf Sets the background/foreground color (see COLOR command)."));
1076 SetConsoleMode (hIn
, ENABLE_PROCESSED_INPUT
);
1078 #ifdef INCLUDE_CMD_CHDIR
1082 #ifdef FATURE_ALIASES
1088 for (i
= 1; i
< argc
; i
++)
1090 if (!_tcsicmp (argv
[i
], _T("/p")))
1092 if (!IsValidFileName (_T("\\autoexec.bat")))
1094 #ifdef INCLUDE_CMD_DATE
1095 cmd_date (_T(""), _T(""));
1097 #ifdef INCLUDE_CMD_TIME
1098 cmd_time (_T(""), _T(""));
1103 ParseCommandLine (_T("\\autoexec.bat"));
1107 else if (!_tcsicmp (argv
[i
], _T("/c")))
1109 /* This just runs a program and exits */
1113 _tcscpy (commandline
, argv
[i
]);
1116 _tcscat (commandline
, _T(" "));
1117 _tcscat (commandline
, argv
[i
]);
1120 ParseCommandLine(commandline
);
1121 ExitProcess (ProcessInput (TRUE
));
1128 else if (!_tcsicmp (argv
[i
], _T("/k")))
1130 /* This just runs a program and remains */
1134 _tcscpy (commandline
, argv
[i
]);
1137 _tcscat (commandline
, _T(" "));
1138 _tcscat (commandline
, argv
[i
]);
1141 ParseCommandLine(commandline
);
1144 #ifdef INCLUDE_CMD_COLOR
1145 else if (!_tcsnicmp (argv
[i
], _T("/t:"), 3))
1147 /* process /t (color) argument */
1148 wDefColor
= (WORD
)_tcstoul (&argv
[i
][3], NULL
, 16);
1150 SetScreenColor (wColor
, TRUE
);
1156 /* run cmdstart.bat */
1157 if (IsValidFileName (_T("cmdstart.bat")))
1159 ParseCommandLine (_T("cmdstart.bat"));
1161 else if (IsValidFileName (_T("\\cmdstart.bat")))
1163 ParseCommandLine (_T("\\cmdstart.bat"));
1168 /* try to run cmdstart.bat from install dir */
1171 _tcscpy (commandline
, argv
[0]);
1172 p
= _tcsrchr (commandline
, _T('\\')) + 1;
1173 _tcscpy (p
, _T("cmdstart.bat"));
1175 if (IsValidFileName (_T("commandline")))
1177 ConErrPrintf (_T("Running %s...\n", commandline
));
1178 ParseCommandLine (commandline
);
1183 #ifdef FEATURE_DIR_STACK
1184 /* initialize directory stack */
1185 InitDirectoryStack ();
1189 #ifdef FEATURE_HISTORY
1190 /*initialize history*/
1194 /* Set COMSPEC environment variable */
1195 if (0 != GetModuleFileName (NULL
, ModuleName
, _MAX_PATH
+ 1))
1197 ModuleName
[_MAX_PATH
] = _T('\0');
1198 SetEnvironmentVariable (_T("COMSPEC"), ModuleName
);
1201 /* add ctrl break handler */
1206 static VOID
Cleanup (int argc
, TCHAR
*argv
[])
1208 /* run cmdexit.bat */
1209 if (IsValidFileName (_T("cmdexit.bat")))
1211 ConErrPrintf (_T("Running cmdexit.bat...\n"));
1212 ParseCommandLine (_T("cmdexit.bat"));
1214 else if (IsValidFileName (_T("\\cmdexit.bat")))
1216 ConErrPrintf (_T("Running \\cmdexit.bat...\n"));
1217 ParseCommandLine (_T("\\cmdexit.bat"));
1222 /* try to run cmdexit.bat from install dir */
1223 TCHAR commandline
[CMDLINE_LENGTH
];
1226 _tcscpy (commandline
, argv
[0]);
1227 p
= _tcsrchr (commandline
, _T('\\')) + 1;
1228 _tcscpy (p
, _T("cmdexit.bat"));
1230 if (IsValidFileName (_T("commandline")))
1232 ConErrPrintf (_T("Running %s...\n"), commandline
);
1233 ParseCommandLine (commandline
);
1238 #ifdef FEATURE_ALIASES
1242 #ifdef FEATURE_DIECTORY_STACK
1243 /* destroy directory stack */
1244 DestroyDirectoryStack ();
1247 #ifdef INCLUDE_CMD_CHDIR
1251 #ifdef FEATURE_HISTORY
1256 /* remove ctrl break handler */
1257 RemoveBreakHandler ();
1258 SetConsoleMode( GetStdHandle( STD_INPUT_HANDLE
),
1259 ENABLE_LINE_INPUT
| ENABLE_PROCESSED_INPUT
| ENABLE_ECHO_INPUT
);
1264 PWCHAR
* _CommandLineToArgvW(PWCHAR lpCmdLine
, int *pNumArgs
)
1266 PWCHAR
* argvw
= NULL
;
1267 PWCHAR ptr
= lpCmdLine
;
1274 while(lpCmdLine
&& *lpCmdLine
)
1276 while (iswspace(*lpCmdLine
)) lpCmdLine
++;
1279 if ((NumArgs
% 10)==0)
1281 PWCHAR
* old_argvw
= argvw
;
1282 argvw
= malloc((NumArgs
+ 10) * sizeof(PWCHAR
));
1283 memcpy(argvw
, old_argvw
, NumArgs
* sizeof(PWCHAR
));
1286 ptr
= wcschr(lpCmdLine
, L
' ');
1289 len
= ptr
- lpCmdLine
;
1293 len
= wcslen(lpCmdLine
);
1295 str
= malloc((len
+ 1) * sizeof(WCHAR
));
1296 memcpy(str
, lpCmdLine
, len
* sizeof(WCHAR
));
1303 *pNumArgs
= NumArgs
;
1315 int main (int argc
, char *argv
[])
1318 CONSOLE_SCREEN_BUFFER_INFO Info
;
1324 argv
= _CommandLineToArgvW(GetCommandLineW(), &argc
);
1326 argv
= CommandLineToArgvW(GetCommandLineW(), &argc
);
1332 hConsole
= CreateFile(_T("CONOUT$"), GENERIC_READ
|GENERIC_WRITE
,
1333 FILE_SHARE_READ
|FILE_SHARE_WRITE
, NULL
,
1334 OPEN_EXISTING
, 0, NULL
);
1335 if (GetConsoleScreenBufferInfo(hConsole
, &Info
) == FALSE
)
1337 ConErrPrintf (_T("GetConsoleScreenBufferInfo: Error: %ld\n"), GetLastError());
1340 wColor
= Info
.wAttributes
;
1343 /* check switches on command-line */
1344 Initialize(argc
, argv
);
1346 /* call prompt routine */
1347 nExitCode
= ProcessInput(FALSE
);
1349 /* do the cleanup */
1350 Cleanup(argc
, argv
);