2 * CMD - Wine-compatible command line interface.
4 * Copyright (C) 1999 - 2001 D A Pickles
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23 * - Cannot handle parameters in quotes
24 * - Lots of functionality missing from builtins
30 const char * const inbuilt[] = {"ATTRIB", "CALL", "CD", "CHDIR", "CLS", "COPY", "CTTY",
31 "DATE", "DEL", "DIR", "ECHO", "ERASE", "FOR", "GOTO",
32 "HELP", "IF", "LABEL", "MD", "MKDIR", "MOVE", "PATH", "PAUSE",
33 "PROMPT", "REM", "REN", "RENAME", "RD", "RMDIR", "SET", "SHIFT",
34 "TIME", "TITLE", "TYPE", "VERIFY", "VER", "VOL",
35 "ENDLOCAL", "SETLOCAL", "PUSHD", "POPD", "EXIT" };
39 int echo_mode = 1, verify_mode = 0;
40 static int opt_c, opt_k, opt_s;
41 const char nyi[] = "Not Yet Implemented\n\n";
42 const char newline[] = "\n";
43 const char version_string[] = "CMD Version " PACKAGE_VERSION "\n\n";
44 const char anykey[] = "Press Return key to continue: ";
45 char quals[MAX_PATH], param1[MAX_PATH], param2[MAX_PATH];
46 BATCH_CONTEXT *context = NULL;
47 static HANDLE old_stdin = INVALID_HANDLE_VALUE, old_stdout = INVALID_HANDLE_VALUE;
49 /*****************************************************************************
50 * Main entry point. This is a console application so we have a main() not a
54 int main (int argc, char *argv[])
62 opt_c=opt_k=opt_q=opt_s=0;
66 if ((*argv)[0]!='/' || (*argv)[1]=='\0') {
72 if (tolower(c)=='c') {
74 } else if (tolower(c)=='q') {
76 } else if (tolower(c)=='k') {
78 } else if (tolower(c)=='s') {
80 } else if (tolower(c)=='t' || tolower(c)=='x' || tolower(c)=='y') {
81 /* Ignored for compatibility with Windows */
86 else /* handle `cmd /cnotepad.exe` and `cmd /x/c ...` */
89 if (opt_c || opt_k) /* break out of parsing immediately after c or k */
102 /* opt_s left unflagged if the command starts with and contains exactly
103 * one quoted string (exactly two quote characters). The quoted string
104 * must be an executable name that has whitespace and must not have the
105 * following characters: &<>()@^| */
107 /* Build the command to execute */
110 for (arg = argv; *arg; arg++)
112 int has_space,bcount;
118 if( !*a ) has_space=1;
123 if (*a==' ' || *a=='\t') {
125 } else if (*a=='"') {
126 /* doubling of '\' preceding a '"',
127 * plus escaping of said '"'
136 len+=(a-*arg)+1 /* for the separating space */;
139 len+=2; /* for the quotes */
147 /* check argv[0] for a space and invalid characters */
152 if (*p=='&' || *p=='<' || *p=='>' || *p=='(' || *p==')'
153 || *p=='@' || *p=='^' || *p=='|') {
163 cmd = HeapAlloc(GetProcessHeap(), 0, len);
168 for (arg = argv; *arg; arg++)
170 int has_space,has_quote;
173 /* Check for quotes and spaces in this argument */
174 has_space=has_quote=0;
176 if( !*a ) has_space=1;
178 if (*a==' ' || *a=='\t') {
182 } else if (*a=='"') {
190 /* Now transfer it to the command line */
207 /* Double all the '\\' preceding this '"', plus one */
208 for (i=0;i<=bcount;i++)
227 p--; /* remove last space */
230 /* strip first and last quote characters if opt_s; check for invalid
231 * executable is done later */
232 if (opt_s && *cmd=='\"')
233 WCMD_opt_s_strip_quotes(cmd);
237 /* If we do a "wcmd /c command", we don't want to allocate a new
238 * console since the command returns immediately. Rather, we use
239 * the currently allocated input and output handles. This allows
240 * us to pipe to and read from the command interpreter.
242 if (strchr(cmd,'|') != NULL)
245 WCMD_process_command(cmd);
246 HeapFree(GetProcessHeap(), 0, cmd);
250 SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), ENABLE_LINE_INPUT |
251 ENABLE_ECHO_INPUT | ENABLE_PROCESSED_INPUT);
252 SetConsoleTitle("Wine Command Prompt");
255 WCMD_process_command(cmd);
256 HeapFree(GetProcessHeap(), 0, cmd);
260 * If there is an AUTOEXEC.BAT file, try to execute it.
263 GetFullPathName ("\\autoexec.bat", sizeof(string), string, NULL);
264 h = CreateFile (string, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
265 if (h != INVALID_HANDLE_VALUE) {
268 WCMD_batch_command (string);
273 * Loop forever getting commands and executing them.
279 ReadFile (GetStdHandle(STD_INPUT_HANDLE), string, sizeof(string), &count, NULL);
281 string[count-1] = '\0'; /* ReadFile output is not null-terminated! */
282 if (string[count-2] == '\r') string[count-2] = '\0'; /* Under Windoze we get CRLF! */
283 if (lstrlen (string) != 0) {
284 if (strchr(string,'|') != NULL) {
288 WCMD_process_command (string);
296 /*****************************************************************************
297 * Process one command. If the command is EXIT this routine does not return.
298 * We will recurse through here executing batch files.
302 void WCMD_process_command (char *command)
306 DWORD count, creationDisposition;
309 SECURITY_ATTRIBUTES sa;
312 * Replace errorlevel with current value (This shrinks in
313 * place and hence no need to reallocate the memory yet)
316 while ((p = strchr(p, '%'))) {
317 if (CompareString (LOCALE_USER_DEFAULT,
318 NORM_IGNORECASE | SORT_STRINGSORT,
319 (p+1), 11, "ERRORLEVEL%", -1) == 2) {
321 sprintf(output, "%d", errorlevel);
331 * Expand up environment variables.
333 len = ExpandEnvironmentStrings (command, NULL, 0);
334 cmd = HeapAlloc( GetProcessHeap(), 0, len );
335 status = ExpandEnvironmentStrings (command, cmd, len);
338 HeapFree( GetProcessHeap(), 0, cmd );
343 * Changing default drive has to be handled as a special case.
346 if ((cmd[1] == ':') && IsCharAlpha (cmd[0]) && (strlen(cmd) == 2)) {
347 status = SetCurrentDirectory (cmd);
348 if (!status) WCMD_print_error ();
349 HeapFree( GetProcessHeap(), 0, cmd );
353 /* Don't issue newline WCMD_output (newline); @JED*/
355 sa.nLength = sizeof(sa);
356 sa.lpSecurityDescriptor = NULL;
357 sa.bInheritHandle = TRUE;
359 * Redirect stdin and/or stdout if required.
362 if ((p = strchr(cmd,'<')) != NULL) {
363 h = CreateFile (WCMD_parameter (++p, 0, NULL), GENERIC_READ, FILE_SHARE_READ, &sa, OPEN_EXISTING,
364 FILE_ATTRIBUTE_NORMAL, NULL);
365 if (h == INVALID_HANDLE_VALUE) {
367 HeapFree( GetProcessHeap(), 0, cmd );
370 old_stdin = GetStdHandle (STD_INPUT_HANDLE);
371 SetStdHandle (STD_INPUT_HANDLE, h);
373 if ((p = strchr(cmd,'>')) != NULL) {
376 creationDisposition = OPEN_ALWAYS;
380 creationDisposition = CREATE_ALWAYS;
382 h = CreateFile (WCMD_parameter (p, 0, NULL), GENERIC_WRITE, 0, &sa, creationDisposition,
383 FILE_ATTRIBUTE_NORMAL, NULL);
384 if (h == INVALID_HANDLE_VALUE) {
386 HeapFree( GetProcessHeap(), 0, cmd );
389 if (SetFilePointer (h, 0, NULL, FILE_END) ==
390 INVALID_SET_FILE_POINTER) {
393 old_stdout = GetStdHandle (STD_OUTPUT_HANDLE);
394 SetStdHandle (STD_OUTPUT_HANDLE, h);
396 if ((p = strchr(cmd,'<')) != NULL) *p = '\0';
399 * Strip leading whitespaces, and a '@' if supplied
401 whichcmd = WCMD_strtrim_leading_spaces(cmd);
402 if (whichcmd[0] == '@') whichcmd++;
405 * Check if the command entered is internal. If it is, pass the rest of the
406 * line down to the command. If not try to run a program.
410 while (IsCharAlphaNumeric(whichcmd[count])) {
413 for (i=0; i<=WCMD_EXIT; i++) {
414 if (CompareString (LOCALE_USER_DEFAULT, NORM_IGNORECASE | SORT_STRINGSORT,
415 whichcmd, count, inbuilt[i], -1) == 2) break;
417 p = WCMD_strtrim_leading_spaces (&whichcmd[count]);
418 WCMD_parse (p, quals, param1, param2);
422 WCMD_setshow_attrib ();
425 WCMD_run_program (p, 1);
429 WCMD_setshow_default ();
432 WCMD_clear_screen ();
441 WCMD_setshow_date ();
451 WCMD_echo(&whichcmd[count]);
476 WCMD_setshow_path (p);
482 WCMD_setshow_prompt ();
501 WCMD_setshow_env (p);
507 WCMD_setshow_time ();
510 if (strlen(&whichcmd[count]) > 0)
511 WCMD_title(&whichcmd[count+1]);
535 WCMD_run_program (whichcmd, 0);
537 HeapFree( GetProcessHeap(), 0, cmd );
538 if (old_stdin != INVALID_HANDLE_VALUE) {
539 CloseHandle (GetStdHandle (STD_INPUT_HANDLE));
540 SetStdHandle (STD_INPUT_HANDLE, old_stdin);
541 old_stdin = INVALID_HANDLE_VALUE;
543 if (old_stdout != INVALID_HANDLE_VALUE) {
544 CloseHandle (GetStdHandle (STD_OUTPUT_HANDLE));
545 SetStdHandle (STD_OUTPUT_HANDLE, old_stdout);
546 old_stdout = INVALID_HANDLE_VALUE;
550 static void init_msvcrt_io_block(STARTUPINFO* st)
553 /* fetch the parent MSVCRT info block if any, so that the child can use the
554 * same handles as its grand-father
556 st_p.cb = sizeof(STARTUPINFO);
557 GetStartupInfo(&st_p);
558 st->cbReserved2 = st_p.cbReserved2;
559 st->lpReserved2 = st_p.lpReserved2;
560 if (st_p.cbReserved2 && st_p.lpReserved2 &&
561 (old_stdin != INVALID_HANDLE_VALUE || old_stdout != INVALID_HANDLE_VALUE))
563 /* Override the entries for fd 0,1,2 if we happened
564 * to change those std handles (this depends on the way wcmd sets
565 * it's new input & output handles)
567 size_t sz = max(sizeof(unsigned) + (sizeof(char) + sizeof(HANDLE)) * 3, st_p.cbReserved2);
568 BYTE* ptr = HeapAlloc(GetProcessHeap(), 0, sz);
571 unsigned num = *(unsigned*)st_p.lpReserved2;
572 char* flags = (char*)(ptr + sizeof(unsigned));
573 HANDLE* handles = (HANDLE*)(flags + num * sizeof(char));
575 memcpy(ptr, st_p.lpReserved2, st_p.cbReserved2);
576 st->cbReserved2 = sz;
577 st->lpReserved2 = ptr;
579 #define WX_OPEN 0x01 /* see dlls/msvcrt/file.c */
580 if (num <= 0 || (flags[0] & WX_OPEN))
582 handles[0] = GetStdHandle(STD_INPUT_HANDLE);
585 if (num <= 1 || (flags[1] & WX_OPEN))
587 handles[1] = GetStdHandle(STD_OUTPUT_HANDLE);
590 if (num <= 2 || (flags[2] & WX_OPEN))
592 handles[2] = GetStdHandle(STD_ERROR_HANDLE);
600 /******************************************************************************
603 * Execute a command line as an external program. If no extension given then
604 * precedence is given to .BAT files. Must allow recursion.
606 * called is 1 if the program was invoked with a CALL command - removed
607 * from command -. It is only used for batch programs.
609 * FIXME: Case sensitivity in suffixes!
612 void WCMD_run_program (char *command, int called) {
615 PROCESS_INFORMATION pe;
621 char filetorun[MAX_PATH];
623 WCMD_parse (command, quals, param1, param2); /* Quick way to get the filename */
624 if (!(*param1) && !(*param2))
626 if (strpbrk (param1, "/\\:") == NULL) { /* No explicit path given */
627 char *ext = strrchr( param1, '.' );
628 if (!ext || !strcasecmp( ext, ".bat"))
630 if (SearchPath (NULL, param1, ".bat", sizeof(filetorun), filetorun, NULL)) {
631 WCMD_batch (filetorun, command, called);
635 if (!ext || !strcasecmp( ext, ".cmd"))
637 if (SearchPath (NULL, param1, ".cmd", sizeof(filetorun), filetorun, NULL)) {
638 WCMD_batch (filetorun, command, called);
643 else { /* Explicit path given */
644 char *ext = strrchr( param1, '.' );
645 if (ext && (!strcasecmp( ext, ".bat" ) || !strcasecmp( ext, ".cmd" )))
647 WCMD_batch (param1, command, called);
651 if (ext && strpbrk( ext, "/\\:" )) ext = NULL;
654 strcpy (filetorun, param1);
655 strcat (filetorun, ".bat");
656 h = CreateFile (filetorun, GENERIC_READ, FILE_SHARE_READ,
657 NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
658 if (h != INVALID_HANDLE_VALUE) {
660 WCMD_batch (param1, command, called);
666 /* No batch file found, assume executable */
668 hinst = FindExecutable (param1, NULL, filetorun);
669 if ((INT_PTR)hinst < 32)
672 console = SHGetFileInfo (filetorun, 0, &psfi, sizeof(psfi), SHGFI_EXETYPE);
674 ZeroMemory (&st, sizeof(STARTUPINFO));
675 st.cb = sizeof(STARTUPINFO);
676 init_msvcrt_io_block(&st);
678 status = CreateProcess (NULL, command, NULL, NULL, TRUE,
679 0, NULL, NULL, &st, &pe);
680 if ((opt_c || opt_k) && !opt_s && !status
681 && GetLastError()==ERROR_FILE_NOT_FOUND && command[0]=='\"') {
682 /* strip first and last quote characters and try again */
683 WCMD_opt_s_strip_quotes(command);
685 WCMD_run_program(command, called);
690 /* If a command fails to launch, it sets errorlevel 9009 - which
691 does not seem to have any associated constant definition */
695 if (!console) errorlevel = 0;
698 if (!HIWORD(console)) WaitForSingleObject (pe.hProcess, INFINITE);
699 GetExitCodeProcess (pe.hProcess, &errorlevel);
700 if (errorlevel == STILL_ACTIVE) errorlevel = 0;
702 CloseHandle(pe.hProcess);
703 CloseHandle(pe.hThread);
706 /******************************************************************************
709 * Display the prompt on STDout
713 void WCMD_show_prompt (void) {
716 char out_string[MAX_PATH], curdir[MAX_PATH], prompt_string[MAX_PATH];
719 status = GetEnvironmentVariable ("PROMPT", prompt_string, sizeof(prompt_string));
720 if ((status == 0) || (status > sizeof(prompt_string))) {
721 lstrcpy (prompt_string, "$P$G");
733 switch (toupper(*p)) {
741 GetDateFormat (LOCALE_USER_DEFAULT, DATE_SHORTDATE, NULL, NULL, q, MAX_PATH);
754 status = GetCurrentDirectory (sizeof(curdir), curdir);
760 status = GetCurrentDirectory (sizeof(curdir), curdir);
770 GetTimeFormat (LOCALE_USER_DEFAULT, 0, NULL, NULL, q, MAX_PATH);
774 lstrcat (q, version_string);
785 WCMD_output_asis (out_string);
788 /****************************************************************************
791 * Print the message for GetLastError
794 void WCMD_print_error (void) {
799 error_code = GetLastError ();
800 status = FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
801 NULL, error_code, 0, (LPTSTR) &lpMsgBuf, 0, NULL);
803 WCMD_output ("FIXME: Cannot display message for error %d, status %d\n",
804 error_code, GetLastError());
807 WCMD_output_asis (lpMsgBuf);
808 LocalFree ((HLOCAL)lpMsgBuf);
809 WCMD_output_asis (newline);
813 /*******************************************************************
814 * WCMD_parse - parse a command into parameters and qualifiers.
816 * On exit, all qualifiers are concatenated into q, the first string
817 * not beginning with "/" is in p1 and the
818 * second in p2. Any subsequent non-qualifier strings are lost.
819 * Parameters in quotes are handled.
822 void WCMD_parse (char *s, char *q, char *p1, char *p2) {
826 *q = *p1 = *p2 = '\0';
831 while ((*s != '\0') && (*s != ' ') && *s != '/') {
832 *q++ = toupper (*s++);
842 while ((*s != '\0') && (*s != '"')) {
843 if (p == 0) *p1++ = *s++;
844 else if (p == 1) *p2++ = *s++;
847 if (p == 0) *p1 = '\0';
848 if (p == 1) *p2 = '\0';
855 while ((*s != '\0') && (*s != ' ') && (*s != '\t')) {
856 if (p == 0) *p1++ = *s++;
857 else if (p == 1) *p2++ = *s++;
860 if (p == 0) *p1 = '\0';
861 if (p == 1) *p2 = '\0';
867 /*******************************************************************
868 * WCMD_output - send output to current standard output device.
872 void WCMD_output (const char *format, ...) {
879 ret = vsnprintf (string, sizeof( string), format, ap);
881 if( ret >= sizeof( string)) {
882 WCMD_output_asis("ERR: output truncated in WCMD_output\n" );
883 string[sizeof( string) -1] = '\0';
885 WCMD_output_asis(string);
889 static int line_count;
890 static int max_height;
891 static BOOL paged_mode;
893 void WCMD_enter_paged_mode(void)
895 CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
897 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &consoleInfo))
898 max_height = consoleInfo.dwSize.Y;
902 line_count = 5; /* keep 5 lines from previous output */
905 void WCMD_leave_paged_mode(void)
910 /*******************************************************************
911 * WCMD_output_asis - send output to current standard output device.
912 * without formatting eg. when message contains '%'
915 void WCMD_output_asis (const char *message) {
922 if ((ptr = strchr(message, '\n')) != NULL) ptr++;
923 WriteFile (GetStdHandle(STD_OUTPUT_HANDLE), message,
924 (ptr) ? ptr - message : lstrlen(message), &count, NULL);
926 if (++line_count >= max_height - 1) {
928 WCMD_output_asis (anykey);
929 ReadFile (GetStdHandle(STD_INPUT_HANDLE), string, sizeof(string), &count, NULL);
932 } while ((message = ptr) != NULL);
934 WriteFile (GetStdHandle(STD_OUTPUT_HANDLE), message, lstrlen(message), &count, NULL);
939 /***************************************************************************
940 * WCMD_strtrim_leading_spaces
942 * Remove leading spaces from a string. Return a pointer to the first
943 * non-space character. Does not modify the input string
946 char *WCMD_strtrim_leading_spaces (char *string) {
951 while (*ptr == ' ') ptr++;
955 /*************************************************************************
956 * WCMD_strtrim_trailing_spaces
958 * Remove trailing spaces from a string. This routine modifies the input
959 * string by placing a null after the last non-space character
962 void WCMD_strtrim_trailing_spaces (char *string) {
966 ptr = string + lstrlen (string) - 1;
967 while ((*ptr == ' ') && (ptr >= string)) {
973 /*************************************************************************
974 * WCMD_opt_s_strip_quotes
976 * Remove first and last quote characters, preserving all other text
979 void WCMD_opt_s_strip_quotes(char *cmd) {
980 char *src = cmd + 1, *dest = cmd, *lastq = NULL;
981 while((*dest=*src) != '\0') {
988 while ((*dest++=*lastq++) != 0)
993 /*************************************************************************
996 * Handle pipes within a command - the DOS way using temporary files.
999 void WCMD_pipe (char *command) {
1002 char temp_path[MAX_PATH], temp_file[MAX_PATH], temp_file2[MAX_PATH], temp_cmd[1024];
1004 GetTempPath (sizeof(temp_path), temp_path);
1005 GetTempFileName (temp_path, "CMD", 0, temp_file);
1006 p = strchr(command, '|');
1008 wsprintf (temp_cmd, "%s > %s", command, temp_file);
1009 WCMD_process_command (temp_cmd);
1011 while ((p = strchr(command, '|'))) {
1013 GetTempFileName (temp_path, "CMD", 0, temp_file2);
1014 wsprintf (temp_cmd, "%s < %s > %s", command, temp_file, temp_file2);
1015 WCMD_process_command (temp_cmd);
1016 DeleteFile (temp_file);
1017 lstrcpy (temp_file, temp_file2);
1020 wsprintf (temp_cmd, "%s < %s", command, temp_file);
1021 WCMD_process_command (temp_cmd);
1022 DeleteFile (temp_file);