1 /* $Id: cmd.c,v 1.5 2003/08/08 15:52:32 weiden 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.
137 BOOL bExit
= FALSE
; /* indicates EXIT was typed */
138 BOOL bCanExit
= TRUE
; /* indicates if this shell is exitable */
139 BOOL bCtrlBreak
= FALSE
; /* Ctrl-Break or Ctrl-C hit */
140 BOOL bIgnoreEcho
= FALSE
; /* Ignore 'newline' before 'cls' */
141 INT nErrorLevel
= 0; /* Errorlevel of last launched external program */
142 BOOL bChildProcessRunning
= FALSE
;
143 DWORD dwChildProcessId
= 0;
149 #ifdef INCLUDE_CMD_COLOR
150 WORD wColor
; /* current color */
151 WORD wDefColor
; /* default color */
156 * is character a delimeter when used on first word?
160 static BOOL
IsDelimiter (TCHAR c
)
162 return (c
== _T('/') || c
== _T('=') || c
== _T('\0') || _istspace (c
));
167 * This command (in first) was not found in the command table
169 * first - first word on command line
170 * rest - rest of command line
174 Execute (LPTSTR first
, LPTSTR rest
)
176 TCHAR szFullName
[MAX_PATH
];
178 TCHAR szWindowTitle
[MAX_PATH
];
180 DWORD dwExitCode
= 0;
183 DebugPrintf (_T("Execute: \'%s\' \'%s\'\n"), first
, rest
);
186 /* check for a drive change */
187 if ((_istalpha (first
[0])) && (!_tcscmp (first
+ 1, _T(":"))))
190 if (!SetCurrentDirectory(first
))
191 /* Guess they changed disc or something, handle that gracefully and get to root */
198 working
= SetCurrentDirectory(str
);
201 if (!working
) ConErrPuts (INVALIDDRIVE
);
206 /* get the PATH environment variable and parse it */
207 /* search the PATH environment variable for the binary */
208 if (!SearchForExecutable (first
, szFullName
))
210 error_bad_command ();
215 GetConsoleTitle (szWindowTitle
, MAX_PATH
);
218 /* check if this is a .BAT or .CMD file */
219 if (!_tcsicmp (_tcsrchr (szFullName
, _T('.')), _T(".bat")) ||
220 !_tcsicmp (_tcsrchr (szFullName
, _T('.')), _T(".cmd")))
223 DebugPrintf (_T("[BATCH: %s %s]\n"), szFullName
, rest
);
225 Batch (szFullName
, first
, rest
);
229 /* exec the program */
230 TCHAR szFullCmdLine
[CMDLINE_LENGTH
];
231 PROCESS_INFORMATION prci
;
235 DebugPrintf (_T("[EXEC: %s %s]\n"), szFullName
, rest
);
237 /* build command line for CreateProcess() */
238 _tcscpy (szFullCmdLine
, first
);
239 _tcscat (szFullCmdLine
, _T(" "));
240 _tcscat (szFullCmdLine
, rest
);
242 /* fill startup info */
243 memset (&stui
, 0, sizeof (STARTUPINFO
));
244 stui
.cb
= sizeof (STARTUPINFO
);
245 stui
.dwFlags
= STARTF_USESHOWWINDOW
;
246 stui
.wShowWindow
= SW_SHOWDEFAULT
;
248 // return console to standard mode
249 SetConsoleMode (GetStdHandle(STD_INPUT_HANDLE
),
250 ENABLE_LINE_INPUT
| ENABLE_PROCESSED_INPUT
| ENABLE_ECHO_INPUT
);
252 if (CreateProcess (szFullName
,
257 CREATE_NEW_PROCESS_GROUP
,
263 /* FIXME: Protect this with critical section */
264 bChildProcessRunning
= TRUE
;
265 dwChildProcessId
= prci
.dwProcessId
;
267 WaitForSingleObject (prci
.hProcess
, INFINITE
);
269 /* FIXME: Protect this with critical section */
270 bChildProcessRunning
= FALSE
;
272 GetExitCodeProcess (prci
.hProcess
, &dwExitCode
);
273 nErrorLevel
= (INT
)dwExitCode
;
274 CloseHandle (prci
.hThread
);
275 CloseHandle (prci
.hProcess
);
279 ErrorMessage (GetLastError (),
280 _T("Error executing CreateProcess()!!\n"));
282 // restore console mode
283 SetConsoleMode( GetStdHandle( STD_INPUT_HANDLE
),
284 ENABLE_PROCESSED_INPUT
);
288 SetConsoleTitle (szWindowTitle
);
294 * look through the internal commands and determine whether or not this
295 * command is one of them. If it is, call the command. If not, call
296 * execute to run it as an external program.
298 * line - the command line of the program to run
303 DoCommand (LPTSTR line
)
305 TCHAR com
[CMDLINE_LENGTH
]; /* the first word in the command */
308 LPTSTR rest
= line
; /* pointer to the rest of the command line */
313 DebugPrintf (_T("DoCommand: (\'%s\')\n"), line
);
316 /* Skip over initial white space */
317 while (_istspace (*rest
))
322 /* Anything to do ? */
325 if (*rest
== _T('"'))
327 /* treat quoted words specially */
331 while(*rest
!= _T('\0') && *rest
!= _T('"'))
332 *cp
++ = _totlower (*rest
++);
336 while (!IsDelimiter (*rest
))
337 *cp
++ = _totlower (*rest
++);
341 /* Terminate first word */
344 /* commands are limited to MAX_PATH */
345 if(_tcslen(com
) > MAX_PATH
)
351 /* Skip over whitespace to rest of line */
352 while (_istspace (*rest
))
355 /* Scan internal command table */
356 for (cmdptr
= cmds
;; cmdptr
++)
358 /* If end of table execute ext cmd */
359 if (cmdptr
->name
== NULL
)
365 if (!_tcscmp (com
, cmdptr
->name
))
367 cmdptr
->func (com
, rest
);
371 /* The following code handles the case of commands like CD which
372 * are recognised even when the command name and parameter are
373 * not space separated.
379 /* Get length of command name */
380 cl
= _tcslen (cmdptr
->name
);
382 if ((cmdptr
->flags
& CMD_SPECIAL
) &&
383 (!_tcsncmp (cmdptr
->name
, com
, cl
)) &&
384 (_tcschr (_T("\\.-"), *(com
+ cl
))))
386 /* OK its one of the specials...*/
388 /* Terminate first word properly */
391 /* Call with new rest */
392 cmdptr
->func (com
, cstart
+ cl
);
401 * process the command line and execute the appropriate functions
402 * full input/output redirection and piping are supported
405 VOID
ParseCommandLine (LPTSTR cmd
)
407 TCHAR cmdline
[CMDLINE_LENGTH
];
409 #ifdef FEATURE_REDIRECTION
410 TCHAR in
[CMDLINE_LENGTH
] = _T("");
411 TCHAR out
[CMDLINE_LENGTH
] = _T("");
412 TCHAR err
[CMDLINE_LENGTH
] = _T("");
413 TCHAR szTempPath
[MAX_PATH
] = _T(".\\");
414 TCHAR szFileName
[2][MAX_PATH
] = {_T(""), _T("")};
415 HANDLE hFile
[2] = {INVALID_HANDLE_VALUE
, INVALID_HANDLE_VALUE
};
423 #endif /* FEATURE_REDIRECTION */
425 _tcscpy (cmdline
, cmd
);
429 DebugPrintf (_T("ParseCommandLine: (\'%s\')\n"), s
);
432 #ifdef FEATURE_ALIASES
433 /* expand all aliases */
434 ExpandAlias (s
, CMDLINE_LENGTH
);
435 #endif /* FEATURE_ALIAS */
437 #ifdef FEATURE_REDIRECTION
438 /* find the temp path to store temporary files */
439 GetTempPath (MAX_PATH
, szTempPath
);
440 if (szTempPath
[_tcslen (szTempPath
) - 1] != _T('\\'))
441 _tcscat (szTempPath
, _T("\\"));
443 /* get the redirections from the command line */
444 num
= GetRedirection (s
, in
, out
, err
, &nRedirFlags
);
446 /* more efficient, but do we really need to do this? */
447 for (t
= in
; _istspace (*t
); t
++)
451 for (t
= out
; _istspace (*t
); t
++)
455 for (t
= err
; _istspace (*t
); t
++)
459 /* Set up the initial conditions ... */
460 /* preserve STDIN, STDOUT and STDERR handles */
461 hOldConIn
= GetStdHandle (STD_INPUT_HANDLE
);
462 hOldConOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
463 hOldConErr
= GetStdHandle (STD_ERROR_HANDLE
);
469 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
471 hFile
= CreateFile (in
, GENERIC_READ
, FILE_SHARE_READ
, &sa
, OPEN_EXISTING
,
472 FILE_ATTRIBUTE_NORMAL
, NULL
);
473 if (hFile
== INVALID_HANDLE_VALUE
)
475 ConErrPrintf (_T("Can't redirect input from file %s\n"), in
);
479 if (!SetStdHandle (STD_INPUT_HANDLE
, hFile
))
481 ConErrPrintf (_T("Can't redirect input from file %s\n"), in
);
485 DebugPrintf (_T("Input redirected from: %s\n"), in
);
489 /* Now do all but the last pipe command */
490 *szFileName
[0] = _T('\0');
491 hFile
[0] = INVALID_HANDLE_VALUE
;
495 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
497 /* Create unique temporary file name */
498 GetTempFileName (szTempPath
, _T("CMD"), 0, szFileName
[1]);
500 /* Set current stdout to temporary file */
501 hFile
[1] = CreateFile (szFileName
[1], GENERIC_WRITE
, 0, &sa
,
502 TRUNCATE_EXISTING
, FILE_ATTRIBUTE_TEMPORARY
, NULL
);
503 SetStdHandle (STD_OUTPUT_HANDLE
, hFile
[1]);
507 /* close stdout file */
508 SetStdHandle (STD_OUTPUT_HANDLE
, hOldConOut
);
509 if ((hFile
[1] != INVALID_HANDLE_VALUE
) && (hFile
[1] != hOldConOut
))
511 CloseHandle (hFile
[1]);
512 hFile
[1] = INVALID_HANDLE_VALUE
;
515 /* close old stdin file */
516 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
517 if ((hFile
[0] != INVALID_HANDLE_VALUE
) && (hFile
[0] != hOldConIn
))
519 /* delete old stdin file, if it is a real file */
520 CloseHandle (hFile
[0]);
521 hFile
[0] = INVALID_HANDLE_VALUE
;
522 DeleteFile (szFileName
[0]);
523 *szFileName
[0] = _T('\0');
526 /* copy stdout file name to stdin file name */
527 _tcscpy (szFileName
[0], szFileName
[1]);
528 *szFileName
[1] = _T('\0');
530 /* open new stdin file */
531 hFile
[0] = CreateFile (szFileName
[0], GENERIC_READ
, 0, &sa
,
532 OPEN_EXISTING
, FILE_ATTRIBUTE_TEMPORARY
, NULL
);
533 SetStdHandle (STD_INPUT_HANDLE
, hFile
[0]);
535 s
= s
+ _tcslen (s
) + 1;
538 /* Now set up the end conditions... */
539 /* redirect STDOUT */
542 /* Final output to here */
544 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
546 hFile
= CreateFile (out
, GENERIC_WRITE
, FILE_SHARE_READ
, &sa
,
547 (nRedirFlags
& OUTPUT_APPEND
) ? OPEN_ALWAYS
: CREATE_ALWAYS
,
548 FILE_ATTRIBUTE_NORMAL
, NULL
);
549 if (hFile
== INVALID_HANDLE_VALUE
)
551 ConErrPrintf (_T("Can't redirect to file %s\n"), out
);
555 if (!SetStdHandle (STD_OUTPUT_HANDLE
, hFile
))
557 ConErrPrintf (_T("Can't redirect to file %s\n"), out
);
561 if (nRedirFlags
& OUTPUT_APPEND
)
565 if (GetFileType (hFile
) == FILE_TYPE_DISK
)
566 SetFilePointer (hFile
, 0, &lHighPos
, FILE_END
);
569 DebugPrintf (_T("Output redirected to: %s\n"), out
);
572 else if (hOldConOut
!= INVALID_HANDLE_VALUE
)
574 /* Restore original stdout */
575 HANDLE hOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
576 SetStdHandle (STD_OUTPUT_HANDLE
, hOldConOut
);
577 if (hOldConOut
!= hOut
)
579 hOldConOut
= INVALID_HANDLE_VALUE
;
582 /* redirect STDERR */
585 /* Final output to here */
587 SECURITY_ATTRIBUTES sa
= {sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
589 if (!_tcscmp (err
, out
))
592 DebugPrintf (_T("Stdout and stderr will use the same file!!\n"));
594 DuplicateHandle (GetCurrentProcess (),
595 GetStdHandle (STD_OUTPUT_HANDLE
),
596 GetCurrentProcess (),
597 &hFile
, 0, TRUE
, DUPLICATE_SAME_ACCESS
);
601 hFile
= CreateFile (err
,
605 (nRedirFlags
& ERROR_APPEND
) ? OPEN_ALWAYS
: CREATE_ALWAYS
,
606 FILE_ATTRIBUTE_NORMAL
,
608 if (hFile
== INVALID_HANDLE_VALUE
)
610 ConErrPrintf (_T("Can't redirect to file %s\n"), err
);
614 if (!SetStdHandle (STD_ERROR_HANDLE
, hFile
))
616 ConErrPrintf (_T("Can't redirect to file %s\n"), err
);
620 if (nRedirFlags
& ERROR_APPEND
)
624 if (GetFileType (hFile
) == FILE_TYPE_DISK
)
625 SetFilePointer (hFile
, 0, &lHighPos
, FILE_END
);
628 DebugPrintf (_T("Error redirected to: %s\n"), err
);
631 else if (hOldConErr
!= INVALID_HANDLE_VALUE
)
633 /* Restore original stderr */
634 HANDLE hErr
= GetStdHandle (STD_ERROR_HANDLE
);
635 SetStdHandle (STD_ERROR_HANDLE
, hOldConErr
);
636 if (hOldConErr
!= hErr
)
638 hOldConErr
= INVALID_HANDLE_VALUE
;
642 /* process final command */
645 #ifdef FEATURE_REDIRECTION
646 /* close old stdin file */
647 #if 0 /* buggy implementation */
648 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
649 if ((hFile
[0] != INVALID_HANDLE_VALUE
) &&
650 (hFile
[0] != hOldConIn
))
652 /* delete old stdin file, if it is a real file */
653 CloseHandle (hFile
[0]);
654 hFile
[0] = INVALID_HANDLE_VALUE
;
655 DeleteFile (szFileName
[0]);
656 *szFileName
[0] = _T('\0');
659 /* Restore original STDIN */
660 if (hOldConIn
!= INVALID_HANDLE_VALUE
)
662 HANDLE hIn
= GetStdHandle (STD_INPUT_HANDLE
);
663 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
664 if (hOldConIn
!= hIn
)
666 hOldConIn
= INVALID_HANDLE_VALUE
;
671 DebugPrintf (_T("Can't restore STDIN! Is invalid!!\n"), out
);
674 #endif /* buggy implementation */
677 if (hOldConIn
!= INVALID_HANDLE_VALUE
)
679 HANDLE hIn
= GetStdHandle (STD_INPUT_HANDLE
);
680 SetStdHandle (STD_INPUT_HANDLE
, hOldConIn
);
681 if (hIn
== INVALID_HANDLE_VALUE
)
684 DebugPrintf (_T("Previous STDIN is invalid!!\n"));
689 if (GetFileType (hIn
) == FILE_TYPE_DISK
)
693 CloseHandle (hFile
[0]);
694 hFile
[0] = INVALID_HANDLE_VALUE
;
695 DeleteFile (szFileName
[0]);
696 *szFileName
[0] = _T('\0');
701 DebugPrintf (_T("hFile[0] and hIn dont match!!!\n"));
709 /* Restore original STDOUT */
710 if (hOldConOut
!= INVALID_HANDLE_VALUE
)
712 HANDLE hOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
713 SetStdHandle (STD_OUTPUT_HANDLE
, hOldConOut
);
714 if (hOldConOut
!= hOut
)
716 hOldConOut
= INVALID_HANDLE_VALUE
;
719 /* Restore original STDERR */
720 if (hOldConErr
!= INVALID_HANDLE_VALUE
)
722 HANDLE hErr
= GetStdHandle (STD_ERROR_HANDLE
);
723 SetStdHandle (STD_ERROR_HANDLE
, hOldConErr
);
724 if (hOldConErr
!= hErr
)
726 hOldConErr
= INVALID_HANDLE_VALUE
;
728 #endif /* FEATURE_REDIRECTION */
733 * do the prompt/input/process loop
738 ProcessInput (BOOL bFlag
)
740 TCHAR commandline
[CMDLINE_LENGTH
];
741 TCHAR readline
[CMDLINE_LENGTH
];
749 /* if no batch input then... */
750 if (!(ip
= ReadBatchLine (&bEchoThisLine
)))
755 ReadCommand (readline
, CMDLINE_LENGTH
);
757 bEchoThisLine
= FALSE
;
781 if ((tp
= FindArg (*ip
- _T('0'))))
783 cp
= stpcpy (cp
, tp
);
791 cp
+= _stprintf (cp
, _T("%u"), nErrorLevel
);
796 tp
= _tcschr(ip
, _T('%'));
798 (tp
<= _tcschr(ip
, _T(' ')) - 1))
803 /* FIXME: This is just a quick hack!! */
804 /* Do a proper memory allocation!! */
805 if (GetEnvironmentVariable (ip
, evar
, 512))
806 cp
= stpcpy (cp
, evar
);
826 /* strip trailing spaces */
827 while ((--cp
>= commandline
) && _istspace (*cp
));
829 *(cp
+ 1) = _T('\0');
832 /* Echo batch file line */
836 ConOutPuts (commandline
);
841 ParseCommandLine (commandline
);
842 if (bEcho
&& !bIgnoreEcho
)
847 while (!bCanExit
|| !bExit
);
854 * control-break handler.
856 BOOL
BreakHandler (DWORD dwCtrlType
)
858 if ((dwCtrlType
!= CTRL_C_EVENT
) &&
859 (dwCtrlType
!= CTRL_BREAK_EVENT
))
862 if (bChildProcessRunning
== TRUE
)
864 GenerateConsoleCtrlEvent (CTRL_C_EVENT
,
869 /* FIXME: Handle batch files */
871 /* FIXME: Print "^C" */
878 VOID
AddBreakHandler (VOID
)
881 SetConsoleCtrlHandler ((PHANDLER_ROUTINE
)&BreakHandler
,
887 VOID
RemoveBreakHandler (VOID
)
890 SetConsoleCtrlHandler (NULL
, FALSE
);
896 * show commands and options that are available.
902 /* print command list */
903 ConOutPrintf (_T("\nInternal commands available:\n"));
906 /* print feature list */
907 ConOutPuts (_T("\nFeatures available:"));
908 #ifdef FEATURE_ALIASES
909 ConOutPuts (_T(" [aliases]"));
911 #ifdef FEATURE_HISTORY
912 ConOutPuts (_T(" [history]"));
914 #ifdef FEATURE_UNIX_FILENAME_COMPLETION
915 ConOutPuts (_T(" [unix filename completion]"));
917 #ifdef FEATURE_DIRECTORY_STACK
918 ConOutPuts (_T(" [directory stack]"));
920 #ifdef FEATURE_REDIRECTION
921 ConOutPuts (_T(" [redirections and piping]"));
923 ConOutChar (_T('\n'));
927 * set up global initializations and process parameters
929 * argc - number of parameters to command.com
930 * argv - command-line parameters
934 Initialize (int argc
, TCHAR
* argv
[])
936 TCHAR commandline
[CMDLINE_LENGTH
];
937 TCHAR ModuleName
[_MAX_PATH
+ 1];
940 TCHAR
*ptr
, *cmdLine
;
946 DebugPrintf (_T("[command args:\n"));
947 for (x
= 0; x
< argc
; x
++)
949 DebugPrintf (_T("%d. %s\n"), x
, argv
[x
]);
951 DebugPrintf (_T("]\n"));
954 /* get version information */
955 osvi
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
956 GetVersionEx (&osvi
);
960 /* get default input and output console handles */
961 hOut
= GetStdHandle (STD_OUTPUT_HANDLE
);
962 hIn
= GetStdHandle (STD_INPUT_HANDLE
);
965 if (argc
>= 2 && !_tcsncmp (argv
[1], _T("/?"), 2))
967 ConOutPuts (_T("Starts a new instance of the ReactOS command line interpreter.\n"
969 "CMD [/[C|K] command][/P][/Q][/T:bf]\n"
971 " /C command Runs the specified command and terminates.\n"
972 " /K command Runs the specified command and remains.\n"
973 " /P CMD becomes permanent and runs autoexec.bat\n"
974 " (cannot be terminated).\n"
975 " /T:bf Sets the background/foreground color (see COLOR command)."));
978 SetConsoleMode (hIn
, ENABLE_PROCESSED_INPUT
);
980 #ifdef INCLUDE_CMD_CHDIR
984 #ifdef FATURE_ALIASES
990 for (i
= 1; i
< argc
; i
++)
992 if (!_tcsicmp (argv
[i
], _T("/p")))
994 if (!IsValidFileName (_T("\\autoexec.bat")))
996 #ifdef INCLUDE_CMD_DATE
997 cmd_date (_T(""), _T(""));
999 #ifdef INCLUDE_CMD_TIME
1000 cmd_time (_T(""), _T(""));
1005 ParseCommandLine (_T("\\autoexec.bat"));
1009 else if (!_tcsicmp (argv
[i
], _T("/c")))
1011 /* This just runs a program and exits */
1015 _tcscpy (commandline
, argv
[i
]);
1018 _tcscat (commandline
, _T(" "));
1019 _tcscat (commandline
, argv
[i
]);
1022 ParseCommandLine(commandline
);
1023 ExitProcess (ProcessInput (TRUE
));
1030 else if (!_tcsicmp (argv
[i
], _T("/k")))
1032 /* This just runs a program and remains */
1036 _tcscpy (commandline
, argv
[i
]);
1039 _tcscat (commandline
, _T(" "));
1040 _tcscat (commandline
, argv
[i
]);
1043 ParseCommandLine(commandline
);
1046 #ifdef INCLUDE_CMD_COLOR
1047 else if (!_tcsnicmp (argv
[i
], _T("/t:"), 3))
1049 /* process /t (color) argument */
1050 wDefColor
= (WORD
)_tcstoul (&argv
[i
][3], NULL
, 16);
1052 SetScreenColor (wColor
, TRUE
);
1058 /* run cmdstart.bat */
1059 if (IsValidFileName (_T("cmdstart.bat")))
1061 ParseCommandLine (_T("cmdstart.bat"));
1063 else if (IsValidFileName (_T("\\cmdstart.bat")))
1065 ParseCommandLine (_T("\\cmdstart.bat"));
1070 /* try to run cmdstart.bat from install dir */
1073 _tcscpy (commandline
, argv
[0]);
1074 p
= _tcsrchr (commandline
, _T('\\')) + 1;
1075 _tcscpy (p
, _T("cmdstart.bat"));
1077 if (IsValidFileName (_T("commandline")))
1079 ConErrPrintf (_T("Running %s...\n", commandline
));
1080 ParseCommandLine (commandline
);
1085 #ifdef FEATURE_DIR_STACK
1086 /* initialize directory stack */
1087 InitDirectoryStack ();
1091 #ifdef FEATURE_HISTORY
1092 /*initialize history*/
1096 /* Set COMSPEC environment variable */
1097 if (0 != GetModuleFileName (NULL
, ModuleName
, _MAX_PATH
+ 1))
1099 ModuleName
[_MAX_PATH
] = _T('\0');
1100 SetEnvironmentVariable (_T("COMSPEC"), ModuleName
);
1103 /* add ctrl break handler */
1108 static VOID
Cleanup (int argc
, TCHAR
*argv
[])
1110 /* run cmdexit.bat */
1111 if (IsValidFileName (_T("cmdexit.bat")))
1113 ConErrPrintf (_T("Running cmdexit.bat...\n"));
1114 ParseCommandLine (_T("cmdexit.bat"));
1116 else if (IsValidFileName (_T("\\cmdexit.bat")))
1118 ConErrPrintf (_T("Running \\cmdexit.bat...\n"));
1119 ParseCommandLine (_T("\\cmdexit.bat"));
1124 /* try to run cmdexit.bat from install dir */
1125 TCHAR commandline
[CMDLINE_LENGTH
];
1128 _tcscpy (commandline
, argv
[0]);
1129 p
= _tcsrchr (commandline
, _T('\\')) + 1;
1130 _tcscpy (p
, _T("cmdexit.bat"));
1132 if (IsValidFileName (_T("commandline")))
1134 ConErrPrintf (_T("Running %s...\n"), commandline
);
1135 ParseCommandLine (commandline
);
1140 #ifdef FEATURE_ALIASES
1144 #ifdef FEATURE_DIECTORY_STACK
1145 /* destroy directory stack */
1146 DestroyDirectoryStack ();
1149 #ifdef INCLUDE_CMD_CHDIR
1153 #ifdef FEATURE_HISTORY
1158 /* remove ctrl break handler */
1159 RemoveBreakHandler ();
1160 SetConsoleMode( GetStdHandle( STD_INPUT_HANDLE
),
1161 ENABLE_LINE_INPUT
| ENABLE_PROCESSED_INPUT
| ENABLE_ECHO_INPUT
);
1166 PWCHAR
* _CommandLineToArgvW(PWCHAR lpCmdLine
, int *pNumArgs
)
1168 PWCHAR
* argvw
= NULL
;
1169 PWCHAR ptr
= lpCmdLine
;
1176 while(lpCmdLine
&& *lpCmdLine
)
1178 while (iswspace(*lpCmdLine
)) lpCmdLine
++;
1181 if ((NumArgs
% 10)==0)
1183 PWCHAR
* old_argvw
= argvw
;
1184 argvw
= malloc((NumArgs
+ 10) * sizeof(PWCHAR
));
1185 memcpy(argvw
, old_argvw
, NumArgs
* sizeof(PWCHAR
));
1188 ptr
= wcschr(lpCmdLine
, L
' ');
1191 len
= ptr
- lpCmdLine
;
1195 len
= wcslen(lpCmdLine
);
1197 str
= malloc((len
+ 1) * sizeof(WCHAR
));
1198 memcpy(str
, lpCmdLine
, len
* sizeof(WCHAR
));
1205 *pNumArgs
= NumArgs
;
1217 int main (int argc
, char *argv
[])
1220 CONSOLE_SCREEN_BUFFER_INFO Info
;
1226 argv
= _CommandLineToArgvW(GetCommandLineW(), &argc
);
1228 argv
= CommandLineToArgvW(GetCommandLineW(), &argc
);
1237 hConsole
= CreateFile(_T("CONOUT$"), GENERIC_READ
|GENERIC_WRITE
,
1238 FILE_SHARE_READ
|FILE_SHARE_WRITE
, NULL
,
1239 OPEN_EXISTING
, 0, NULL
);
1240 if (GetConsoleScreenBufferInfo(hConsole
, &Info
) == FALSE
)
1242 ConErrPrintf (_T("GetConsoleScreenBufferInfo: Error: %ld\n"), GetLastError());
1245 wColor
= Info
.wAttributes
;
1248 /* check switches on command-line */
1249 Initialize(argc
, argv
);
1251 /* call prompt routine */
1252 nExitCode
= ProcessInput(FALSE
);
1254 /* do the cleanup */
1255 Cleanup(argc
, argv
);