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", "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]);
529 WCMD_run_program (whichcmd
, 0);
531 HeapFree( GetProcessHeap(), 0, cmd
);
532 if (old_stdin
!= INVALID_HANDLE_VALUE
) {
533 CloseHandle (GetStdHandle (STD_INPUT_HANDLE
));
534 SetStdHandle (STD_INPUT_HANDLE
, old_stdin
);
535 old_stdin
= INVALID_HANDLE_VALUE
;
537 if (old_stdout
!= INVALID_HANDLE_VALUE
) {
538 CloseHandle (GetStdHandle (STD_OUTPUT_HANDLE
));
539 SetStdHandle (STD_OUTPUT_HANDLE
, old_stdout
);
540 old_stdout
= INVALID_HANDLE_VALUE
;
544 static void init_msvcrt_io_block(STARTUPINFO
* st
)
547 /* fetch the parent MSVCRT info block if any, so that the child can use the
548 * same handles as its grand-father
550 st_p
.cb
= sizeof(STARTUPINFO
);
551 GetStartupInfo(&st_p
);
552 st
->cbReserved2
= st_p
.cbReserved2
;
553 st
->lpReserved2
= st_p
.lpReserved2
;
554 if (st_p
.cbReserved2
&& st_p
.lpReserved2
&&
555 (old_stdin
!= INVALID_HANDLE_VALUE
|| old_stdout
!= INVALID_HANDLE_VALUE
))
557 /* Override the entries for fd 0,1,2 if we happened
558 * to change those std handles (this depends on the way wcmd sets
559 * it's new input & output handles)
561 size_t sz
= max(sizeof(unsigned) + (sizeof(char) + sizeof(HANDLE
)) * 3, st_p
.cbReserved2
);
562 BYTE
* ptr
= HeapAlloc(GetProcessHeap(), 0, sz
);
565 unsigned num
= *(unsigned*)st_p
.lpReserved2
;
566 char* flags
= (char*)(ptr
+ sizeof(unsigned));
567 HANDLE
* handles
= (HANDLE
*)(flags
+ num
* sizeof(char));
569 memcpy(ptr
, st_p
.lpReserved2
, st_p
.cbReserved2
);
570 st
->cbReserved2
= sz
;
571 st
->lpReserved2
= ptr
;
573 #define WX_OPEN 0x01 /* see dlls/msvcrt/file.c */
574 if (num
<= 0 || (flags
[0] & WX_OPEN
))
576 handles
[0] = GetStdHandle(STD_INPUT_HANDLE
);
579 if (num
<= 1 || (flags
[1] & WX_OPEN
))
581 handles
[1] = GetStdHandle(STD_OUTPUT_HANDLE
);
584 if (num
<= 2 || (flags
[2] & WX_OPEN
))
586 handles
[2] = GetStdHandle(STD_ERROR_HANDLE
);
594 /******************************************************************************
597 * Execute a command line as an external program. If no extension given then
598 * precedence is given to .BAT files. Must allow recursion.
600 * called is 1 if the program was invoked with a CALL command - removed
601 * from command -. It is only used for batch programs.
603 * FIXME: Case sensitivity in suffixes!
606 void WCMD_run_program (char *command
, int called
) {
609 PROCESS_INFORMATION pe
;
615 char filetorun
[MAX_PATH
];
617 WCMD_parse (command
, quals
, param1
, param2
); /* Quick way to get the filename */
618 if (!(*param1
) && !(*param2
))
620 if (strpbrk (param1
, "/\\:") == NULL
) { /* No explicit path given */
621 char *ext
= strrchr( param1
, '.' );
622 if (!ext
|| !strcasecmp( ext
, ".bat"))
624 if (SearchPath (NULL
, param1
, ".bat", sizeof(filetorun
), filetorun
, NULL
)) {
625 WCMD_batch (filetorun
, command
, called
);
629 if (!ext
|| !strcasecmp( ext
, ".cmd"))
631 if (SearchPath (NULL
, param1
, ".cmd", sizeof(filetorun
), filetorun
, NULL
)) {
632 WCMD_batch (filetorun
, command
, called
);
637 else { /* Explicit path given */
638 char *ext
= strrchr( param1
, '.' );
639 if (ext
&& (!strcasecmp( ext
, ".bat" ) || !strcasecmp( ext
, ".cmd" )))
641 WCMD_batch (param1
, command
, called
);
645 if (ext
&& strpbrk( ext
, "/\\:" )) ext
= NULL
;
648 strcpy (filetorun
, param1
);
649 strcat (filetorun
, ".bat");
650 h
= CreateFile (filetorun
, GENERIC_READ
, FILE_SHARE_READ
,
651 NULL
, OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, NULL
);
652 if (h
!= INVALID_HANDLE_VALUE
) {
654 WCMD_batch (param1
, command
, called
);
660 /* No batch file found, assume executable */
662 hinst
= FindExecutable (param1
, NULL
, filetorun
);
663 if ((INT_PTR
)hinst
< 32)
666 console
= SHGetFileInfo (filetorun
, 0, &psfi
, sizeof(psfi
), SHGFI_EXETYPE
);
668 ZeroMemory (&st
, sizeof(STARTUPINFO
));
669 st
.cb
= sizeof(STARTUPINFO
);
670 init_msvcrt_io_block(&st
);
672 status
= CreateProcess (NULL
, command
, NULL
, NULL
, TRUE
,
673 0, NULL
, NULL
, &st
, &pe
);
674 if ((opt_c
|| opt_k
) && !opt_s
&& !status
675 && GetLastError()==ERROR_FILE_NOT_FOUND
&& command
[0]=='\"') {
676 /* strip first and last quote characters and try again */
677 WCMD_opt_s_strip_quotes(command
);
679 WCMD_run_program(command
, called
);
684 /* If a command fails to launch, it sets errorlevel 9009 - which
685 does not seem to have any associated constant definition */
689 if (!console
) errorlevel
= 0;
692 if (!HIWORD(console
)) WaitForSingleObject (pe
.hProcess
, INFINITE
);
693 GetExitCodeProcess (pe
.hProcess
, &errorlevel
);
694 if (errorlevel
== STILL_ACTIVE
) errorlevel
= 0;
696 CloseHandle(pe
.hProcess
);
697 CloseHandle(pe
.hThread
);
700 /******************************************************************************
703 * Display the prompt on STDout
707 void WCMD_show_prompt (void) {
710 char out_string
[MAX_PATH
], curdir
[MAX_PATH
], prompt_string
[MAX_PATH
];
713 status
= GetEnvironmentVariable ("PROMPT", prompt_string
, sizeof(prompt_string
));
714 if ((status
== 0) || (status
> sizeof(prompt_string
))) {
715 lstrcpy (prompt_string
, "$P$G");
727 switch (toupper(*p
)) {
735 GetDateFormat (LOCALE_USER_DEFAULT
, DATE_SHORTDATE
, NULL
, NULL
, q
, MAX_PATH
);
748 status
= GetCurrentDirectory (sizeof(curdir
), curdir
);
754 status
= GetCurrentDirectory (sizeof(curdir
), curdir
);
764 GetTimeFormat (LOCALE_USER_DEFAULT
, 0, NULL
, NULL
, q
, MAX_PATH
);
768 lstrcat (q
, version_string
);
779 WCMD_output_asis (out_string
);
782 /****************************************************************************
785 * Print the message for GetLastError
788 void WCMD_print_error (void) {
793 error_code
= GetLastError ();
794 status
= FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
,
795 NULL
, error_code
, 0, (LPTSTR
) &lpMsgBuf
, 0, NULL
);
797 WCMD_output ("FIXME: Cannot display message for error %d, status %d\n",
798 error_code
, GetLastError());
801 WCMD_output_asis (lpMsgBuf
);
802 LocalFree ((HLOCAL
)lpMsgBuf
);
803 WCMD_output_asis (newline
);
807 /*******************************************************************
808 * WCMD_parse - parse a command into parameters and qualifiers.
810 * On exit, all qualifiers are concatenated into q, the first string
811 * not beginning with "/" is in p1 and the
812 * second in p2. Any subsequent non-qualifier strings are lost.
813 * Parameters in quotes are handled.
816 void WCMD_parse (char *s
, char *q
, char *p1
, char *p2
) {
820 *q
= *p1
= *p2
= '\0';
825 while ((*s
!= '\0') && (*s
!= ' ') && *s
!= '/') {
826 *q
++ = toupper (*s
++);
836 while ((*s
!= '\0') && (*s
!= '"')) {
837 if (p
== 0) *p1
++ = *s
++;
838 else if (p
== 1) *p2
++ = *s
++;
841 if (p
== 0) *p1
= '\0';
842 if (p
== 1) *p2
= '\0';
849 while ((*s
!= '\0') && (*s
!= ' ') && (*s
!= '\t')) {
850 if (p
== 0) *p1
++ = *s
++;
851 else if (p
== 1) *p2
++ = *s
++;
854 if (p
== 0) *p1
= '\0';
855 if (p
== 1) *p2
= '\0';
861 /*******************************************************************
862 * WCMD_output - send output to current standard output device.
866 void WCMD_output (const char *format
, ...) {
873 ret
= vsnprintf (string
, sizeof( string
), format
, ap
);
875 if( ret
>= sizeof( string
)) {
876 WCMD_output_asis("ERR: output truncated in WCMD_output\n" );
877 string
[sizeof( string
) -1] = '\0';
879 WCMD_output_asis(string
);
883 static int line_count
;
884 static int max_height
;
885 static BOOL paged_mode
;
887 void WCMD_enter_paged_mode(void)
889 CONSOLE_SCREEN_BUFFER_INFO consoleInfo
;
891 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE
), &consoleInfo
))
892 max_height
= consoleInfo
.dwSize
.Y
;
896 line_count
= 5; /* keep 5 lines from previous output */
899 void WCMD_leave_paged_mode(void)
904 /*******************************************************************
905 * WCMD_output_asis - send output to current standard output device.
906 * without formatting eg. when message contains '%'
909 void WCMD_output_asis (const char *message
) {
916 if ((ptr
= strchr(message
, '\n')) != NULL
) ptr
++;
917 WriteFile (GetStdHandle(STD_OUTPUT_HANDLE
), message
,
918 (ptr
) ? ptr
- message
: lstrlen(message
), &count
, NULL
);
920 if (++line_count
>= max_height
- 1) {
922 WCMD_output_asis (anykey
);
923 ReadFile (GetStdHandle(STD_INPUT_HANDLE
), string
, sizeof(string
), &count
, NULL
);
926 } while ((message
= ptr
) != NULL
);
928 WriteFile (GetStdHandle(STD_OUTPUT_HANDLE
), message
, lstrlen(message
), &count
, NULL
);
933 /***************************************************************************
934 * WCMD_strtrim_leading_spaces
936 * Remove leading spaces from a string. Return a pointer to the first
937 * non-space character. Does not modify the input string
940 char *WCMD_strtrim_leading_spaces (char *string
) {
945 while (*ptr
== ' ') ptr
++;
949 /*************************************************************************
950 * WCMD_strtrim_trailing_spaces
952 * Remove trailing spaces from a string. This routine modifies the input
953 * string by placing a null after the last non-space character
956 void WCMD_strtrim_trailing_spaces (char *string
) {
960 ptr
= string
+ lstrlen (string
) - 1;
961 while ((*ptr
== ' ') && (ptr
>= string
)) {
967 /*************************************************************************
968 * WCMD_opt_s_strip_quotes
970 * Remove first and last quote characters, preserving all other text
973 void WCMD_opt_s_strip_quotes(char *cmd
) {
974 char *src
= cmd
+ 1, *dest
= cmd
, *lastq
= NULL
;
975 while((*dest
=*src
) != '\0') {
982 while ((*dest
++=*lastq
++) != 0)
987 /*************************************************************************
990 * Handle pipes within a command - the DOS way using temporary files.
993 void WCMD_pipe (char *command
) {
996 char temp_path
[MAX_PATH
], temp_file
[MAX_PATH
], temp_file2
[MAX_PATH
], temp_cmd
[1024];
998 GetTempPath (sizeof(temp_path
), temp_path
);
999 GetTempFileName (temp_path
, "CMD", 0, temp_file
);
1000 p
= strchr(command
, '|');
1002 wsprintf (temp_cmd
, "%s > %s", command
, temp_file
);
1003 WCMD_process_command (temp_cmd
);
1005 while ((p
= strchr(command
, '|'))) {
1007 GetTempFileName (temp_path
, "CMD", 0, temp_file2
);
1008 wsprintf (temp_cmd
, "%s < %s > %s", command
, temp_file
, temp_file2
);
1009 WCMD_process_command (temp_cmd
);
1010 DeleteFile (temp_file
);
1011 lstrcpy (temp_file
, temp_file2
);
1014 wsprintf (temp_cmd
, "%s < %s", command
, temp_file
);
1015 WCMD_process_command (temp_cmd
);
1016 DeleteFile (temp_file
);